Spring系列之Redis的两种集成方式
在工作中,我们用到分布式缓存的时候,第一选择就是Redis,今天介绍一下SpringBoot如何集成Redis的,分别使用Jedis和Spring-data-redis两种方式。
一、使用Jedis方式集成
1、增加依赖
<!-- spring-boot-starter-web不是必须的,这里是为了测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<!-- fastjson不是必须的,这里是为了测试-->
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
2、配置项
redis.host=localhost
redis.maxTotal=5
redis.maxIdle=5
redis.testOnBorrow=true
#以下方式也可以,SpringBoot同样能将其解析注入到JedisPoolConfig中
#redis.max-total=3
#redis.max-idle=3
#redis.test-on-borrow=true
3、配置连接池
/**
* @author 公-众-号:程序员阿牛
* 由于Jedis实例本身不非线程安全的,因此我们用JedisPool
*/
@Configuration
public class CommonConfig {
@Bean
@ConfigurationProperties("redis")
public JedisPoolConfig jedisPoolConfig() {
return new JedisPoolConfig();
}
@Bean(destroyMethod = "close")
public JedisPool jedisPool(@Value("${redis.host}") String host) {
return new JedisPool(jedisPoolConfig(), host);
}
}
4、测试
/**
* @author 公-众-号:程序员阿牛
*/
@RestController
public class JedisController {
@Autowired
private JedisPool jedisPool;
@RequestMapping("getUser")
public String getUserFromRedis(){
UserInfo userInfo = new UserInfo();
userInfo.setUserId("A0001");
userInfo.setUserName("张三丰");
userInfo.setAddress("武当山");
jedisPool.getResource().set("userInfo", JSON.toJSONString(userInfo));
UserInfo userInfo1 = JSON.parseObject(jedisPool.getResource().get("userInfo"),UserInfo.class);
return userInfo1.toString();
}
}
运行结果如下:

我们可以自己包装一个RedisClient,来简化我们的操作
使用spring-data-redis
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置项
在application.properties中增加配置
spring.redis.host=localhost
spring.redis.port=6379
3、使用
/**
* @author 公-众-号:程序员阿牛
*/
@RestController
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("getUser2")
public String getUserFromRedis(){
UserInfo userInfo = new UserInfo();
userInfo.setUserId("A0001");
userInfo.setUserName("张三丰");
userInfo.setAddress("武当山");
redisTemplate.opsForValue().set("userInfo", userInfo);
UserInfo userInfo1 = (UserInfo) redisTemplate.opsForValue().get("userInfo");
return userInfo1.toString();
}
}
是的,你只需要引入依赖、加入配置就可以使用Redis了,不要高兴的太早,这里面会有一些坑
4、可能会遇到的坑

使用工具查看我们刚才set的内容,发现key前面多了一串字符,value也是不可见的
原因
使用springdataredis,默认情况下是使用org.springframework.data.redis.serializer.JdkSerializationRedisSerializer这个类来做序列化
具体我们看一下RedisTemplate 代码如何实现的
/**
*在初始化的时候,默认的序列化类是JdkSerializationRedisSerializer
*/
public void afterPropertiesSet() {
super.afterPropertiesSet();
boolean defaultUsed = false;
if (this.defaultSerializer == null) {
this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
}
...省略无关代码
}
如何解决
很简单,自己定义RedisTemplate并指定序列化类即可
/**
* @author 公-众-号:程序员阿牛
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setValueSerializer(jackson2JsonRedisSerializer());
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
@Bean
public RedisSerializer<Object> jackson2JsonRedisSerializer() {
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
return serializer;
}
}
查看运行结果:

哨兵和集群
只需要改一下配置项即可
# 哨兵
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381
#集群
spring.redis.cluster.max-redirects=100
spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384
总结:
以上两种方式都可以,但是还是建议你使用Spring-data-redis,因为Spring经过多年的发展,尤其是Springboot的日渐成熟,已经为我们简化了很多操作。
关注我,下一篇继续

Spring系列之Redis的两种集成方式的更多相关文章
- Redis系列之----Redis的两种持久化机制(RDB和AOF)
Redis的两种持久化机制(RDB和AOF) 什么是持久化 Redis的数据是存储在内存中的,内存中的数据随着服务器的重启或者宕机便会不复存在,在生产环境,服务器宕机更是屡见不鲜,所以,我们希望 ...
- Redis的两种持久化方式-快照持久化和AOF持久化
Redis为了内部数据的安全考虑,会把本身的数据以文件形式保存到硬盘中一份,在服务器重启之后会自动把硬盘的数据恢复到内存(redis)的里边,数据保存到硬盘的过程就称为"持久化"效 ...
- Redis的两种持久化方式-快照持久化(RDB)和AOF持久化
Redis为了内部数据的安全考虑,会把本身的数据以文件形式保存到硬盘中一份,在服务器重启之后会自动把硬盘的数据恢复到内存(redis)的里边,数据保存到硬盘的过程就称为“持久化”效果. redis有两 ...
- Spring的核心api和两种实例化方式
一.spring的核心api Spring有如下的核心api BeanFactory :这是一个工厂,用于生成任意bean.采取延迟加载,第一次getBean时才会初始化Bean Applicatio ...
- Redis的两种持久化方式详细介绍
一,Redis是一款基于内存的数据库,可以持久化,在企业中常用于缓存,相信大家都比较熟悉Redis了,下面主要分享下关于Redis持久化的两种模式 1.半持久化模式(RDB,filesnapshott ...
- redis的两种备份方式
Redis提供了两种持久化选项,分别是RDB和AOF. 默认情况下60秒刷新到disk一次[save 60 10000 当有1w条keys数据被改变时],Redis的数据集保存在叫dump.rdb一个 ...
- [转载] redis 的两种持久化方式及原理
转载自http://www.m690.com/archives/371 Redis是一种高级key-value数据库.它跟memcached类似,不过数据可以持久化,而且支持的数据类型很丰富.有字符串 ...
- Redis的两种连接方式
1.简单连接 import redis conn = redis.Redis(host=) conn.set('foo', 'Bar') print(conn.get('foo')) a = inpu ...
- Spring声明式事务的两种配置方式(注解/xml)
application配置tx:annotation-driven 配置声明式事务tx:TransactionManager 声明式事务需要数据源所以需要配置DataSource 使用:在类或者方法上 ...
随机推荐
- AECC2018同时中英文切换多开使用,加倍提高你的工作效率
最近相信不少人已经更新了AECC2018,升级之后第一件重要的事当然是中英文的切换了,要不然工作中很麻烦.对于一直习惯用中文的人来说,在用模板过程中会出现各种表达式报错极其不方便,而对于习惯英文操作朋 ...
- 关于腾讯云redis 无法外网访问的解决方案
问题简介: 今天购买了一台腾讯云的redis:如图 可是我没有找到 腾讯云提供的外网地址,我该怎么连接呢?百度了一大堆 全部是 在腾讯云服务器上搭建的Redis实例的解决办法.完全不匹配. 开始解决: ...
- Acwing 883高斯消元法的运用
Acwing 883高斯消元法的运用 解线性方程组 Acwing 883 输入一个包含 n 个方程 n 个未知数的线性方程组. 方程组中的系数为实数. 求解这个方程组. 下图为一个包含 m 个方程 n ...
- Flink Streaming状态处理(Working with State)
参考来源: https://www.jianshu.com/p/6ed0ef5e2b74 https://blog.csdn.net/Fenggms/article/details/102855159 ...
- 高德地图——2D转换3D
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script ty ...
- MySQL-存储引擎-1
一.MySQL存储引擎 mysql> create table country( -> country_id smallint unsigned not null auto_increme ...
- uboot常用命令及其使用
环境变量设置 setenv 设置一个环境变量 # 格式:setenv key vlaue setenv bootdelay 5 # 设置uboot启动延时5s 删除一个环境变量 uboot对于一个没有 ...
- Python__requests模块的基本使用
1 - 安装和导入 pip install requests import requests 2 - requsts的请求方法 requests.get('https://www.baidu.com/ ...
- 源码解析.Net中Host主机的构建过程
前言 本篇文章着重讲一下在.Net中Host主机的构建过程,依旧延续之前文章的思路,着重讲解其源码,如果有不知道有哪些用法的同学可以点击这里,废话不多说,咱们直接进入正题 Host构建过程 下图是我自 ...
- Python - break、continue 的使用
前置知识 break.continue 会结合循环使用的,所以要先学会循环哦 python 提供了两种循环语句 for 循环:https://www.cnblogs.com/poloyy/p/1508 ...