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. redis zset 介绍

    $key = 'key'; //新增 zadd($key,分数,标识) //删除某个标识 zrem($key,标识) //查询某个标识的排名(从0开始的 所有在输出的时候要加一) zrevrank($ ...

  2. MySQL总结02

    sql优化 Insert使用批量 查询不要使用*, MySQ需要先查出表里的所有字段,再进行匹配 字符串的查询条件要带引号,否则可能不走索引 备份及恢复 备份 mysqldump -uroot -pp ...

  3. 37-python基础-python3-字典的常用方法-keys()-values()-items()

    有 3 个字典方法,它们将返回类似列表的值,分别对应于字典的键.值和键-值对:keys().values()和 items(). 这些方法返回的值不是真正的列表,它们不能被修改,没有append()方 ...

  4. CF1205B

    CF1205B 由鸽巢原理n比较大的时候直接输出3 然后剩下的就可以跑最小环 #include<iostream> #include<cstdio> #include<c ...

  5. 如何在vue框架中兼容IE

    IE目前已经放弃了自己的独特化,正一步步迎入互联网的主流怀抱.但迫于有用户存在,还是要兼容到IE8,9, 以上. 下面聊一下如何在vue框架中兼容IE 1.首先在index.html <meta ...

  6. JUnit中Assert简单介绍

    junit中的assert方法全部放在Assert类中,总结一下junit类中assert方法的分类.1.assertTrue/False([String message,]boolean condi ...

  7. CSS3 新特性(box-sizing盒模型,背景线性渐变,filter滤镜,calc函数,transition过渡)

    1.盒子模型(box-sizing) CSS3 中可以通过 box-sizing 来指定盒模型,有两个值:即可指定为 content-box.border-box,这样我们计算盒子大小的方式就发生了改 ...

  8. 解决.Net MVC 中出现 非介入式客户端验证规则中的验证类型名称必须唯一。下列验证类型出现重复: required 的bug

    最近在开动科技创新作品的开发,出现了一个让人很烦恼的错误,每次从浏览页跳转到编辑页时就会出现一下错误 非介入式客户端验证规则中的验证类型名称必须唯一.下列验证类型出现重复: required 上一下出 ...

  9. 遇到的css问题

    1.上下两个div高度重叠:原因是上面的div中存在浮动,且没有设置高度,解决方案:外面再套一个div,设置高度或overflow:hidden 2.上下两个div存在间隙:原因是有div的displ ...

  10. Samba服务的安装

    Samba的安装 1.准备环境 Centos7 [root@localhost ~]# systemctl stop firewalld [root@localhost ~]# setenforce ...