自用RedisConfig的配置,更改key为string和value json的序列化,避免set乱的key,使用StringRedisTemplate也可以解决,保证了redis set的值是正确的
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
return redisTemplate;
}
}
与其对应的controller
package com.yase.build.controller;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class RedisController {
@Resource
private RedisTemplate redisTemplate;
@GetMapping("/{key}")
public Object get(@PathVariable String key){
Object o = redisTemplate.opsForValue().get(key);
return o;
}
@GetMapping("/{key}/{value}")
public Object set(@PathVariable String key,@PathVariable String value){
redisTemplate.opsForValue().set(key,value);
return "ok";
}
}