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. C語言中資料結構(struct)的大小

    通常在PC上寫程式時,很少會去管struct會佔掉多少記憶體.當要使用到時,也不會想去用手算到底佔掉多少,大多是直接使用sizeof來做計算.然而sizeof計算出來的值往往不會如我們想的一樣.因為c ...

  2. python 根据余弦定理计算两边的夹角

    前面写过C#的. import numpy def GetAngle(sta_point, mid_point, end_point): ma_x = sta_point.X-mid_point.X ...

  3. fetch bulk collect into 进行批量、快速提取数据的方式

    1.游标的含义 2.oracle 11g 中的三类游标的使用方式 3.oracle 11g中使用 fetch ... bulk collect into 进行批量.快速提取数据的方式 4.根据不同情况 ...

  4. 结对编程收获——UI真的没有那么简单

    结对编程收获——UI真的没有那么简单                                                      詹元成 初看作业要求,心里还有一点欣喜,不就是做一个UI ...

  5. Android Service完全解析(上)

    转载:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的Androi ...

  6. 【学术篇】CF833B TheBakery 分治dp+主席树

    题目の传送门~ 题目大意: 将\(n\)个蛋糕分成恰好\(k\)份, 求每份中包含的蛋糕的种类数之和的最大值. 这题有两种做法. 第一种是线段树优化dp, 我还没有考虑. 另一种就是分治+主席树. 然 ...

  7. KindEditor在eclipse里的配置方法

    KindEditor介绍: kindEditor是一款国产富文本编辑器,类似fckeditor和目前比较流行的百度Ueditor.其产品官方网站为http://kindeditor.net/ Kind ...

  8. Python内部变量与外部变量

    def outer(): x = 'outer x' def inner(): x = 'inner x' print(x) inner() print(x) # 这里的`x`与`x = 'outer ...

  9. div框,左右拖动

    <script type="text/javascript"> function bindResize(el){ //初始化参数 var els = document. ...

  10. Python 项目隔离环境virtualenv--venv

    virtualenv 用来为一个应用创建一套“隔离”的python运行环境. 先安装virtualenv: pip3 install virtualenv 再进入项目目录,或者创建一个项目目录并进入, ...