默认刚导入的redistemplate是不能存入对象的
得去加入配置类才可以
@Configuration
public class Redisconfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
并且由上面代码所示,对象必须实现序列化
同时自动注入的类也要改泛型
@Autowired
private RedisTemplate<String, Object> redistemplate;
存取hash类型
public Map<String, Object> setRedis(String key){
Map<String, Object> map = new HashMap<>();
redistemplate.opsForHash().put("jedishash", "sola", "wow");
map.put("data", redistemplate.opsForHash().get("jedishash", "sola"));
return map;
}
map里存list
public Map<String, Object> setRedis(String key){
Map<String, Object> map = new HashMap<>();
Map<String, Object> maptest = null;
List<Map<String, Object>> list = new LinkedList<>();
for(int i = 1 ; i <=10 ; i++){
maptest = new HashMap<>();
maptest.put("name", i);
maptest.put("age", i);
list.add(maptest);
}
redistemplate.opsForHash().put("jedismaplist", "one", list);
map.put("data", redistemplate.opsForHash().get("jedismaplist", "one"));
return map;
}
存取String类型
public Map<String, Object> setRedis(String key){
Map<String, Object> map = new HashMap<>();
redistemplate.opsForValue().set("jedisString", "jedisStringValue");
String string = redistemplate.opsForValue().get("jedisString");
map.put("jedisString", string);
return map;
}
存储list类型(linkedlist)
public Map<String, Object> setRedis(String key){
Map<String, Object> map = new HashMap<>();
police policemode = null;
int poilceno = 1;
int pollceage = 1;
for(;poilceno <= 10; poilceno++){
policemode = new police();
policemode.setNo(poilceno+"");
policemode.setAge(pollceage+"");
pollceage++;
redistemplate.opsForList().rightPush("jedislist",policemode );
}
//查看所有
map.put("data", redistemplate.opsForList().range("jedislist", 0, -1));
return map;
}
直接装整个集合也可以
public Map<String, Object> setRedis(String key){
Map<String, Object> map = new HashMap<>();
Map<String, Object> maptest = null;
List<Map<String, Object>> list = new LinkedList<>();
for(int i = 1 ; i <=10 ; i++){
maptest = new HashMap<>();
maptest.put("name", i);
maptest.put("age", i);
list.add(maptest);
}
redistemplate.opsForList().rightPushAll("jedislist", list);
map.put("data",redistemplate.opsForList().range("jedislist", 0, -1) );
return map;
}