Spring-boot整合Redis,遇到的问题
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,遇到的问题的更多相关文章
- SpringBoot入门系列(七)Spring Boot整合Redis缓存
前面介绍了Spring Boot 中的整合Mybatis并实现增删改查,.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/ ...
- Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能
Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能 开篇 现在的网站基本都有邮件注册功能,毕竟可以通过邮件定期的给用户发送一些 垃圾邮件 精选推荐
- (转)spring boot整合redis
一篇写的更清晰的文章,包括redis序列化:http://makaidong.com/ncjava/330749_5285125.html 1.项目目录结构 2.引入所需jar包 <!-- Sp ...
- Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis
在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...
- Spring Boot 整合 Redis 实现缓存操作
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 ...
- spring boot整合redis,以及设置缓存过期时间
spring-boot 整合 redis 注:redis服务器要先开启 pom文件: <dependency> <groupId>org.springframework.boo ...
- spring boot 2.x 系列 —— spring boot 整合 redis
文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...
- Spring Boot2 系列教程(二十九)Spring Boot 整合 Redis
经过 Spring Boot 的整合封装与自动化配置,在 Spring Boot 中整合Redis 已经变得非常容易了,开发者只需要引入 Spring Data Redis 依赖,然后简单配下 red ...
- Spring Boot 整合Redis 实现缓存
本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解 ...
- spring boot 整合 redis
自己开发环境需要安装 redis 服务,百度一下很多,下面主要说明Springboot 集成 redis 讲解 我的版本 java8 + redis3.0 + springboot 1.5.9. Sp ...
随机推荐
- 线程组,action to be taken after a sampler error
continue:继续运行后面的请求 start next thread loop:后面的请求不执行,重新循环执行 stop thread:停止所有线程(等待正在执行的线程执行完后,失败的请求后面的 ...
- VIM 单词大小写转换
遇到大小写转换的时候,我觉得首先一个不应该直接放弃的选择就是采用正则表达式以及文本替换功能.不过,针对单个单词的转换在VIM中还有更为简单的方式. 组合命令gUw可以实现把光标当前所在位置的一个单词转 ...
- 爬虫平台设置代理ip
首先从国外一个网站爬取了免费的代理ip信息存到mongodb中:接着代码设置: 在爬虫客户端抽象类中添加属性: 设置代理的代码其实就以下几句: firefoxProfile.setPreference ...
- 欧拉函数(Euler_Function)
一.基本概述在数论,对正整数n,欧拉函数varphi(n)是少于或等于n的数中与n互质的数的数目.此函数以其首名研究者欧拉命名,它又称为Euler's totient function.φ函数.欧拉商 ...
- JSON 和 xml 浅读
1. JSON数据格式 JSON 语法是 JavaScript 对象表示法语法的子集. 数据在名称/值对中:名称是字符串,使用双引号表示.值可以是:数字(整数或浮点数),字符串(在双引号中),数组(在 ...
- 完全卸载win10上的Ubuntu子系统 - Windows Subsystem for Linux(WSL)
Ctrl + R 键入: lxrun /uninstall /full 具体请看 microsoft的说明:Frequently Asked Questions
- SpringBoot 应用程序启动过程探秘
概述 说到接触 SpringBoot 伊始,给我第一映像最深的是有两个关键元素: 对照上面的典型代码,这个两个元素分别是: @SpringBootApplication SpringApplicati ...
- 使用MySQL Workbench查询超时的错误
MySQL Workbench是MySQL提供的连接工具,一直在用它.但是今天运行了一个SQL缺报出如下的错误: errcode 2013 lost connection to mysql serve ...
- C#5.0 异步编程 Async和Await--异步方法的规范和注意事项
要些异步方法要注意一下几点: 异步方法的返回值有三种: 1.没有任何返回值的void 2.返回一个Task任务的Task,可以获得该异步方法的执行状态 3.返回Task<T> 可以获得异步 ...
- (二)Django连接本地mysql异常
Pycharm连接数据库出现错误 管理员身份进入mysql数据库 命令: mysql -u root -p 重新进入mysql 在进入Pycharm发现连接成功