https://docs.spring.io/spring-data/redis/docs/current/reference/html
一.Redis事务
和redis一样RedisTemplate也提供了 multi, exec, discard
相应命令的支持。RedisTemplate不会保证事务中所有操作都是在相同的connection中,一定要在相同连接中可以使用SessionCallback
来执行多个操作。
List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
public List<Object> execute(RedisOperations operations) throws DataAccessException {
operations.multi();
operations.opsForSet().add("key", "value1");
// This will contain the results of all operations in the transaction
return operations.exec();
}
});
System.out.println("Number of items added to set: " + txResults.get(0));
二.添加@Transactional支持
RedisTemplate
默认不由spring事务管理,通过RedisTemplate
的setEnableTransactionSupport(true)
可以开启支持。启用事务支持会将 RedisConnection
通过 ThreadLocal
绑定到当前事务。事务完成并且没报错时,Redis事务执行EXEC
提交,否则执行DISCARD
回滚。事务执行期间Redis写命令都会放入RedisTemplate
的队列中,当事务提交时批量应用,读命令会直接执行。
配置例子:
@Configuration
@EnableTransactionManagement
public class RedisTxContextConfiguration {
@Bean
public StringRedisTemplate redisTemplate() {
StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
// explicitly enable transaction support
template.setEnableTransactionSupport(true);
return template;
}
@Bean
public RedisConnectionFactory redisConnectionFactory() {
// jedis || Lettuce
}
@Bean
public PlatformTransactionManager transactionManager() throws SQLException {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public DataSource dataSource() throws SQLException {
// ...
}
}
Configures a Spring Context to enable declarative transaction management.
Configures RedisTemplate to participate in transactions by binding connections to the current thread.
Transaction management requires a PlatformTransactionManager. Spring Data Redis does not ship with a PlatformTransactionManager implementation. Assuming your application uses JDBC, Spring Data Redis can participate in transactions by using existing transaction managers.