Redis 事务
Redis事务的分析及改进:https://blog.csdn.net/kingmax54212008/article/details/82731199
SpringBoot Redis 事务
配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Configuration @EnableTransactionManagement public class BeanConfig {
@Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(lettuceConnectionFactory); setRedisTemplate(redisTemplate); redisTemplate.setEnableTransactionSupport(true); return redisTemplate; } }
|
业务代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
@Slf4j @Service public class TransactionService {
@Autowired private RedisTemplate<String, Object> redisTemplate;
@Transactional(rollbackFor = Exception.class) public void test1() throws Exception { System.out.println(redisTemplate.opsForValue().get("test1")); redisTemplate.opsForValue().set("test1", "test1"); throw new Exception("异常信息"); }
public void test2(boolean flag, String key) throws Exception { redisTemplate.multi();
redisTemplate.opsForValue().set(key, key); if (flag) { throw new Exception("异常信息"); } redisTemplate.opsForValue().set(key + 2, key + 2);
redisTemplate.exec(); } }
|
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @SpringBootTest class RedisTransactionApplicationTests {
@Autowired TransactionService transactionService;
@Autowired private RedisTemplate<String, Object> redisTemplate;
@Test void redisKey() throws Exception {
transactionService.test2(true, "key2");
} }
|