依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>redis.clients</groupId>-->
<!--<artifactId>jedis</artifactId>-->
<!--<version>2.9.0</version>-->
<!--</dependency>-->
/** Jedis jedis = new Jedis("ip", 6379);
// 直接调用jedis对象的方法,方法名称和redis的命令一致
jedis.set("key1", "test01");
String key1 = jedis.get("key1"); **/
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test(){
String key = "redis_key";
redisTemplate.opsForValue().set(key,"ccccvvvv");
Object o = redisTemplate.opsForValue().get(key);
}
结果:
默认的RedisTemplate的泛型是<Object,Object> ,写代码不方便,需要写好多类型转换的代码;我们需要一个泛型为<String,Object>形式的RedisTemplate.
创建自己的RedisTemplate<String, Object>
/**
* spring-data-redis 默认的RedisTemplate<Object, Object> redisTemplate
* 创建自己的RedisTemplate<String, Object> redisTemplate
* RedisAutoConfiguration 中@ConditionalOnMissingBean({"redisTemplate"}) 如果自己创建了就不会使用默认的了
* @param factory
* @return
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
测试
@Test
public void test(){
String key = "redis_key";
String key2 = "redis_own_template";
redisUtil.set(key2,"values");
}
参考: https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html