1.通过set进redis中的数据,get不到

        String cityKey ="city_"+id;
ValueOperations<String,City> operations = this.redisTemplate.opsForValue();
// 判断缓存中是否存在
if (this.redisTemplate.hasKey(cityKey)){ City city = operations.get(cityKey);
return city;
}
// 从 DB 中获取
City city = this.cityRepository.findById(id).get(); // 添加的缓存中,时间10
operations.set(cityKey,city,, TimeUnit.SECONDS);

在redis-cli 中查看

192.168.6.3:> keys *
 \xac\xed\x00\x05t\x00\x06city_2

发现key值出现 \xac\xed\x00\x05t\x00\x06city_2 key是乱码

原因:序列化是默认用的JdkSerializationRedisSerializer

在redis配置中添加

//设置key序列-String序列化
template.setKeySerializer(new StringRedisSerializer());

2.如果希望java对象以json的方式存储到redis中

通常会在redis配置中添加

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

// 设置value的序列化规则
//json序列化
template.setValueSerializer(jackson2JsonRedisSerializer);

但是进行redis缓存get时会报错:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.redis.springbootredis.pojo.City

 java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.redis.springbootredis.pojo.City
at com.redis.springbootredis.service.impl.CityServiceImpl.findCityById(CityServiceImpl.java:59)
at com.redis.springbootredis.SpringBootRedisApplicationTests.testFindCityById(SpringBootRedisApplicationTests.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

原因:redis中取出的对象数据为json,java.util.LinkedHashMap无法转换成city对象,

解决方式:在redis配置中添加

        //解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);

还有一种方式:就是每次获取到对象数据进行json转换(每一都要转换太麻烦不太建议)

            String str = JSONObject.toJSONString(operations.get(cityKey));
City cityy = JSON.parseObject(str,City.class);

笔者的redis配置类

 import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; /**
* @Author: GWL
* @Description: redis配置
* redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
* 一般redis的序列化方式主要有:字符串序列化、json序列化、xml序列化、jdk序列化
* 默认为 JdkSerializationRedisSerializer
* @Date: Create in 14:43 2019/5/14
*/
@Configuration
public class RedisConfig { @Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisCollectionFactory) {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(redisCollectionFactory); 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的序列化规则
//json序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//String序列化
// template.setValueSerializer(new StringRedisSerializer());
//jdk序列化
// template.setValueSerializer(new JdkSerializationRedisSerializer()); //设置key序列-String序列化
template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new StringRedisSerializer());
template.afterPropertiesSet(); return template;
} }

RedisConfig

再次redis中查看缓存对象:redis中中文乱码,但是存取没影响

192.168.6.3:6379> keys *
1) "city_2"
192.168.6.3:6379> get city_2
"[\"com.redis.springbootredis.pojo.City\",{\"id\":2,\"name\":\"\xe5\xa4\xa9\xe6\xb4\xa5\",\"description\":\"\xe6\xac\xa2\xe8\xbf\x8e\xe4\xbd\xa0\xe6\x9d\xa5\xe6\x8c\xa4\xe5\x9c\xb0\xe9\x93\x81\",\"createDate\":[\"java.sql.Timestamp\",1557737066000]}]"

换个姿势再来一次

如何在get时取到它的中文呢?只需要在redis-cli 后面加上 –raw

192.168.6.3:6379> QUIT
[root@localhost src]# ./redis-cli -h 192.168.6.3 -p 6379 --raw
192.168.6.3:6379> keys *
city_2
192.168.6.3:6379> get city_2
["com.redis.springbootredis.pojo.City",{"id":2,"name":"天津","description":"欢迎你来挤地铁","createDate":["java.sql.Timestamp",1557737066000]}]

有兴趣的朋友可以查看本人的spring-boot-redis:GitHub项目

Spring-boot整合Redis,遇到的问题的更多相关文章

  1. SpringBoot入门系列(七)Spring Boot整合Redis缓存

    前面介绍了Spring Boot 中的整合Mybatis并实现增删改查,.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/ ...

  2. Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能

    Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能 开篇 现在的网站基本都有邮件注册功能,毕竟可以通过邮件定期的给用户发送一些 垃圾邮件 精选推荐

  3. (转)spring boot整合redis

    一篇写的更清晰的文章,包括redis序列化:http://makaidong.com/ncjava/330749_5285125.html 1.项目目录结构 2.引入所需jar包 <!-- Sp ...

  4. Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis

    在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...

  5. Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!   『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』   本文提纲 ...

  6. spring boot整合redis,以及设置缓存过期时间

    spring-boot 整合 redis 注:redis服务器要先开启 pom文件: <dependency> <groupId>org.springframework.boo ...

  7. spring boot 2.x 系列 —— spring boot 整合 redis

    文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...

  8. Spring Boot2 系列教程(二十九)Spring Boot 整合 Redis

    经过 Spring Boot 的整合封装与自动化配置,在 Spring Boot 中整合Redis 已经变得非常容易了,开发者只需要引入 Spring Data Redis 依赖,然后简单配下 red ...

  9. Spring Boot 整合Redis 实现缓存

      本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解   ...

  10. spring boot 整合 redis

    自己开发环境需要安装 redis 服务,百度一下很多,下面主要说明Springboot 集成 redis 讲解 我的版本 java8 + redis3.0 + springboot 1.5.9. Sp ...

随机推荐

  1. Linux NIO 系列(04-1) select

    目录 一.select 机制的优势 二.select API 介绍与使用 2.1 select 2.2 fd_set 集合操作 2.3 select 使用范例 三.深入理解 select 模型: 四. ...

  2. js node.children与node.childNodes与node.firstChild,node,lastChild之间的关系

    博客搬迁,给你带来的不便,敬请谅解! http://www.suanliutudousi.com/2017/11/06/js-node-children%e4%b8%8enode-childnodes ...

  3. JSON工具类的构建(后端版本)

    前言 在前后端交互的选择上,之前一直采用的是模板引擎(因为我只负责后端). 而这次的一个算是作业吧,前后端都是我,所以就研究了一下JSON交互在java web的应用(主要是前端). 优缺点 前后端耦 ...

  4. Pyhon 格式化输出的几种方式

    废话不多说,直接上代码 第一种格式化的输出方式,拼接我就不上了,不建议使用,数据多的时候自己都蒙圈 # -*- coding:utf-8 -*- # Author:覃振鸿 #格式化输出 name=in ...

  5. npm 安装扩展模块时,因缓存报错的问题汇总

    1.缓存报错问题一 :    unexpected end of file 解决方法:运行:npm cache verify  清除缓存 2.缓存报错问题二 :   errno -4048(网上一般说 ...

  6. Codeforces 1167E 尺取法

    题意:给你一个长度为n的数组,以及数组中的数的取值范围1 - m,问有多少个区间[l, r],使得删除了数组中数值为[l, r]的数之后,数组是非递减的. 思路:我们记录一下每一个数出现的最左端和最右 ...

  7. DBCP重连的问题及解决办法(转)

    本文转载:http://lc87624.iteye.com/blog/1734089,欢迎大家阅读原文. 使用数据库连接池时,免不了会遇到断网.数据库挂掉等异常状况,当网络或数据库恢复时,若无法恢复连 ...

  8. day08 python文件操作

    day08 python   一.文件操作     1.文件操作的函数         open(文件名, mode=模式, encoding=字符集)       2.模式: r, w, a, r+ ...

  9. Eclipse maven 明明有jar包 但是不能用

    原因1:没有引入pom.xml依赖 解决: 添加pom.xml依赖

  10. k8s集群的搭建之三:flannel

    一介绍 flannel是CoreOS提供用于解决Dokcer集群跨主机通讯的覆盖网络工具.它的主要思路是:预先留出一个网段,每个主机使用其中一部分,然后每个容器被分配不同的ip:让所有的容器认为大家在 ...