I have redisTemplate that is initialized with connectionFactory and has enabled transaction support. The problem is that redisTemplate.multi();
doesn’t seem to create transaction.
redisTemplate.multi();
redisTemplate.opsForValue().multiGet(Arrays.asList( "test"));
redisTemplate.exec();
No matter what I put between multi and exec, exec always returns error org.springframework.dao.InvalidDataAccessApiUsageException: No ongoing transaction. Did you forget to call multi?
Connection to Redis works, queries that don’t involve transactions work. When I use discard() right after multi() it says org.springframework.data.redis.RedisSystemException: Unknown redis exception; nested exception is java.lang.IllegalStateException: Connection has no active transaction
Any ideas what could be the problem or how could I debug this?
Instead of calling multi()
, exec()
, and other operations directly on the RedisTemplate
, it’s often better to use the execute(
) method with a SessionCallback
. This ensures that all operations are performed on the same connection.
public void performTransaction() {
try {
redisTemplate.execute(new SessionCallback<List<Object>>() {
@Override
public List<Object> execute(RedisOperations operations) throws DataAccessException {
operations.multi();
operations.opsForValue().multiGet(Arrays.asList("test"));
// Add more operations here
return operations.exec();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}