当前,我正在尝试学习spring数据redis
我已经创建了一些测试项目并成功插入了数据,但是在使用管道命令时遇到了问题
这是我的配置文件:
public RedisTemplate<String, String> redisTemplate( JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
和我的存储库:
@Repository
public class PaymentDetailRepoImpl implements PaymentDetailRepo {
@Autowired RedisTemplate<String, String> redisTemplate;
private ValueOperations<String, String> operation;
@PostConstruct
private void init() {
operation = redisTemplate.opsForValue();
}
@Override
public void saveMulti(List<Payment> listModel) {
this.redisTemplate.executePipelined(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
listModel.forEach(model -> {
operation.set(model.getUser(), model.getTotal());
});
return null;
}
});
}
数据已成功导入Redis,但是在交易结束时出现以下错误:
org.springframework.data.redis.RedisSystemException: Unknown redis exception; nested exception is java.lang.NullPointerException
原因:
by: java.lang.NullPointerException: null
at redis.clients.jedis.Transaction.exec(Transaction.java:54)
at org.springframework.data.redis.connection.jedis.JedisConnection.exec(JedisConnection.java:558)
您知道为什么会发生此错误吗?
答案 0 :(得分:0)
遇到类似的错误,设置afterPropertiesSet解决了该问题。有关afterPropertiesSet的更多信息,请参见https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/beans/factory/InitializingBean.html?is-external=true#afterPropertiesSet--。
public RedisTemplate<String, Object> redisTemplate() {
final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory());
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
template.afterPropertiesSet();
return template;
}