使用RedisTemplate来对对象、String等做缓存处理
首先定义一个对象并重写toString方法
public class UserInfo implements Serializable{ private int id; private String name; private String password; private String salt; private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } @Override public String toString(){ return "name="+name+", password="+password+", salt="+salt+", role="+role; } } 自定义RedisConfig文件,自定义RedisTemplate,设定相应的序列化方式 Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ public RedisConfig() { super(); } @Bean public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); return rcm; } @Override public KeyGenerator keyGenerator() { KeyGenerator keyGenerator = new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { StringBuilder sb = new StringBuilder(); sb.append(o.getClass().getName()); sb.append(method.getName()); for (Object obj : objects) { sb.append(obj.toString()); } return sb.toString(); } }; return keyGenerator; } @Override public CacheResolver cacheResolver() { return super.cacheResolver(); } @Override public CacheErrorHandler errorHandler() { return super.errorHandler(); } /** * redis 序列化策略 ,通常情况下key值采用String序列化策略 * StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。StringRedisSerializer * RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。JdkSerializationRedisSerializer * @param factory * @return */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory){ RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); // 使用Jackson2JsonRedisSerialize 替换默认序列化 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); //设置value的序列化方式 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); //设置key的序列化方式 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
对各种RedisTemplate进行操作测试
1 @Test 2 public void getUser() throws Exception { 3 UserInfo userInfo = new UserInfo(); 4 userInfo.setId(4); 5 userInfo.setName("1"); 6 userInfo.setSalt("1"); 7 userInfo.setRole("1"); 8 userInfo.setPassword("1"); 9 UserInfo userInfo1 = new UserInfo(); 10 userInfo.setId(6); 11 userInfo1.setName("2"); 12 userInfo1.setSalt("2"); 13 userInfo1.setRole("2"); 14 userInfo1.setPassword("2"); 15 ArrayList<UserInfo> list = new ArrayList<>(); 16 list.add(userInfo); 17 list.add(userInfo1); 18 19 //redis 基本的key value 20 ValueOperations<String, UserInfo> valueOperations = redisTemplate.opsForValue(); 21 valueOperations.set(String.valueOf(17), userInfo); 22 23 24 /** 25 * ["java.util.ArrayList",[["com.redistest.domain.UserInfo",{"id":6,"name":"1","password":"1","salt":"1","role":"1"}],["com.redistest.domain.UserInfo",{"id":0,"name":"2","password":"2","salt":"2","role":"2"}]]] 26 */ 27 //redis list对象保存, 会存bean的名字 28 ValueOperations<String, List> valueOperations1 = redisTemplate.opsForValue(); 29 valueOperations1.set(String.valueOf(18), list); 30 31 32 33 //redisTemplate.setDefaultSerializer(new Jackson2JsonRedisSerializer<UserInfo>(UserInfo.class)); 34 35 36 //如果用Jackson2JsonRedisSerializer ,存储的有bean的名字,则能直接转换为相应的对象,不需要再做转换 37 //如果存储的string里面没有bean的名字则返回的arrayList里面是 LinkedHasMap, 需要用Jsos转为String再转为Bean 38 ArrayList<UserInfo> arrayList = (ArrayList<UserInfo>) redisTemplate.opsForValue().get(18+""); 39 for (UserInfo o :arrayList){ 40 // JSONObject userInfo = JSONObject.parseObject(JSONObject.toJSONString(o)); 41 // UserInfo userInfo1 = userInfo.toJavaObject(UserInfo.class); 42 System.out.println(o.toString()); 43 } 44 45 // redisTemplate.opsForValue(); 46 // Object o = redisTemplate.opsForValue().get(6+""); 47 // redisTestController.getUser(6); 48 }
不适用RedisTemplate的序列化方式,使用fastJson首先对对象转换为相应的String再进行存储
@Test public void testGson(){ UserInfo userInfo = new UserInfo(); userInfo.setPassword("g"); userInfo.setRole("g"); userInfo.setName("g"); userInfo.setSalt("g"); userInfo.setId(1); //将java的bean作为一个json的字符串存储到redis中 String str = JSONObject.toJSONString(userInfo); redisTemplate.opsForValue().set("g", str); //取出redis的string,转换为UserInfo bean String s = (String) redisTemplate.opsForValue().get("g"); UserInfo userInfo1 = JSONObject.parseObject(s).toJavaObject(UserInfo.class); System.out.println(userInfo1.toString()); }
使用RedisTemplate。fastJson 来对ArrayList对象进行存储
@Test public void testGson(){ UserInfo userInfo = new UserInfo(); userInfo.setPassword("g"); userInfo.setRole("g"); userInfo.setName("g"); userInfo.setSalt("g"); userInfo.setId(1); //将java的bean作为一个json的字符串存储到redis中 String str = JSONObject.toJSONString(userInfo); redisTemplate.opsForValue().set("g", str); //取出redis的string,转换为UserInfo bean String s = (String) redisTemplate.opsForValue().get("g"); UserInfo userInfo1 = JSONObject.parseObject(s).toJavaObject(UserInfo.class); System.out.println(userInfo1.toString()); //测试arrayList对象 ArrayList<UserInfo> arrayList = new ArrayList<>(); UserInfo userInfo2 = new UserInfo(); userInfo2.setPassword("gg"); userInfo2.setRole("ggg"); userInfo2.setName("gg"); userInfo2.setSalt("ggg"); userInfo2.setId(2); arrayList.add(userInfo); arrayList.add(userInfo1); arrayList.add(userInfo2); String s1 = JSON.toJSONString(arrayList); redisTemplate.opsForValue().set("gg", s1); //测试取出对象 String ss = (String) redisTemplate.opsForValue().get("gg"); System.out.println("存储的原始的String字符串"); //[{"id":1,"name":"g","password":"g","role":"g","salt":"g"},{"id":1,"name":"g","password":"g","role":"g","salt":"g"},{"id":2,"name":"gg","password":"gg","role":"ggg","salt":"ggg"}] System.out.println(ss); ArrayList<UserInfo> arrayList1 = JSON.parseObject(ss, new TypeReference<ArrayList<UserInfo>>(){}); System.out.println("转换后单个UserInfo"); for (UserInfo userInfo3 : arrayList1){ System.out.println(userInfo3.toString()); } //ArrayList<UserInfo> arrayList1 = JSONObject.parseObject(ss); }
以下使用FastJson的GenericFastJsonRedisSerializer 对RedisTemplate序列化
//使用fastJson作为默认的序列化方式
GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
redisTemplate.setDefaultSerializer(genericFastJsonRedisSerializer);
@Test public void testFastJsonSerializer(){ UserInfo userInfo = new UserInfo(); userInfo.setId(4); userInfo.setName("1"); userInfo.setSalt("1"); userInfo.setRole("1"); userInfo.setPassword("1"); redisTemplate.opsForValue().set("121", userInfo); //存储到redis的数据将bean的名字作为一个type存储 /** * { "@type": "com.redistest.domain.UserInfo", "id": 4, "name": "1", "password": "1", "role": "1", "salt": "1" } */ System.out.println("获取输出"); UserInfo userInfo1 = (UserInfo) redisTemplate.opsForValue().get("121"); System.out.println(userInfo1.toString()); //测试list /** * [ { "@type": "com.redistest.domain.UserInfo", "id": 4, "name": "1", "password": "1", "role": "1", "salt": "1" }, { "@type": "com.redistest.domain.UserInfo", "id": 4, "name": "1", "password": "1", "role": "1", "salt": "1" } ] */ ArrayList<UserInfo> arrayList1 = new ArrayList<>(); arrayList1.add(userInfo); arrayList1.add(userInfo1); redisTemplate.opsForValue().set("1212", arrayList1); System.out.println("获取arrayList输出"); JSONArray jsonArray = (JSONArray) redisTemplate.opsForValue().get("1212"); ArrayList<UserInfo> arrayList11 = jsonArray.toJavaObject(new TypeReference<ArrayList<UserInfo>>(){}); for (UserInfo userInfo2 : arrayList11){ System.out.println(userInfo2); } }