- application.yml (redis part)
redis:
database: 0
host: 10.0.3.1
port: 6379
password:
- add transaction support
@Configuration
@EnableTransactionManagement
public class RedisConfiguration {
@Autowired
DataSource dataSource;
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
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;
}
}
- add helper class
@Component
public class RedisUtils {
@Autowired
private StringRedisTemplate template;
public void setKey(String key, String value) {
ValueOperations<String, String> ops = template.opsForValue();
ops.set(key, value);
}
public String getValue(String key){
ValueOperations<String, String> ops = this.template.opsForValue();
return ops.get(key);
}
/**
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
*/
}
- Junit testcase
@Test
@Transactional
public void testError() {
ru.setKey("ddd", "aa");
ru.setKey(null, "cc");// 抛出异常
ru.setKey("fff", "cc");
}
- 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/