springboot redis 事务的支持 笔记

  1. application.yml (redis part)
    redis:
      database: 0
      host: 10.0.3.1
      port: 6379
      password:
  1. add transaction support

@Configuration
@EnableTransactionManagement 
public class RedisConfiguration {
    
    @Autowired
    DataSource dataSource;    
    
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        

        template.setEnableTransactionSupport(true);
        
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(name = "stringRedisTemplate")
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
    
    //https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/  
    @Bean    
    public PlatformTransactionManager transactionManager() throws SQLException {       
        return new DataSourceTransactionManager(dataSource()); 
    }

     
    @Bean
    public DataSource dataSource() { 
        return dataSource;
    }
    
}
  1. add helper class
@Component
public class RedisUtils {

    @Autowired
    private StringRedisTemplate template;

    public void setKey(String key, String value) {
        ValueOperations ops = template.opsForValue();
        ops.set(key, value);
    }

    public String getValue(String key){        
        ValueOperations ops = this.template.opsForValue();        
        return ops.get(key);
    }

     /**
      redisTemplate.opsForValue();//操作字符串
      redisTemplate.opsForHash();//操作hash
      redisTemplate.opsForList();//操作list
      redisTemplate.opsForSet();//操作set
      redisTemplate.opsForZSet();//操作有序set

 
      */

}


  1. Junit testcase
 
    @Test
    @Transactional
    public void testError() {
        ru.setKey("ddd", "aa");
        ru.setKey(null, "cc");// 抛出异常
        ru.setKey("fff", "cc");
    }

  1. run , then check redis list result (ddd was not wrote to list)

[root@RedisServer src]# redis-cli -h 10.0.3.1
10.0.3.1:6379> 


10.0.3.1:6379> keys *
1) "myname"
2) "mykey2"

REF: https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/

你可能感兴趣的:(springboot redis 事务的支持 笔记)