spring boot 集成redis 解决value的编码问题

1. pom中添加依赖
        
			org.springframework.boot
			spring-boot-starter-data-redis
		
2. application.yml 中配置redis
spring:
  redis:
    host: localhost
    port: 6379

3. 添加redis 配置类

@Configuration
public class RedisConfig {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Bean
	public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
		RedisTemplate redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(connectionFactory); //创建redis连接

		GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();  // 序列化方式
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringRedisSerializer); // key的序列化方式是string类型
		redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer); //value的序列化方式是 json
		redisTemplate.setHashKeySerializer(stringRedisSerializer);
		redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

		return redisTemplate;
	}
}

    @Autowired
	private RedisTemplate redisTemplate; // 序列化以后可以存储对象
//	@Autowired
//	private StringRedisTemplate stringRedisTemplate;  // 只能存储string类型的

	Hello hello = new Hello();
	hello.setAge(100);
	hello.setName("nihao");
	redisTemplate.opsForValue().set("hello", hello);

		

 

你可能感兴趣的:(redis)