Spring Boot集成Redis集群(Cluster模式)
同样的,我们还是分两种集成方式来介绍,并是以Cluster模式进行集成。另外,还有几篇关于的Windows下Redis的搭建与集成系列文章可做参考
集成jedis
引入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
配置绑定
新增配置
################################################ 连接池配置
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=100
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=2000
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=500
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
################################################ redis集群部署配置
#设置key的生存时间,当key过期时,它会被自动删除
spring.redis.cluster.expire-seconds=120
#设置redis集群的节点信息
spring.redis.cluster.nodes=127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005,127.0.0.1:7006
#设置命令的执行时间,如果超过这个时间,则报错
spring.redis.cluster.command-timeout=5000
新增对应配置映射类RedisPoolProperties
@Component
@PropertySource("classpath:/redis.properties")
public class RedisPoolProperties {
private Integer maxActive;
private Integer maxWait;
private Integer maxIdle;
private Integer minIdle;
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxWait() {
return maxWait;
}
public void setMaxWait(Integer maxWait) {
this.maxWait = maxWait;
}
public Integer getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(Integer maxIdle) {
this.maxIdle = maxIdle;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
@Override
public String toString() {
return "RedisPoolProperties{" +
"maxActive=" + maxActive +
", maxWait=" + maxWait +
", maxIdle=" + maxIdle +
", minIdle=" + minIdle +
'}';
}
}
连接池的配置的在上一篇文章Spring Boot 项目集成Redis已做介绍
注册
拿到集群的相关配置,然后就集群的注册
@Configuration
public class RedisConfig {
@Autowired
private RedisClusterProperties redisClusterProperties;
/* Jedis - 集群、连接池模式 */
@Bean
public JedisCluster jedisCluster(){
/* 切割节点信息 */
String[] nodes = redisClusterProperties.getNodes().split(",");
Set<HostAndPort> hostAndPorts = new HashSet<>();
for (String node : nodes) {
int index = node.indexOf(":");
hostAndPorts.add(new HostAndPort(node.substring(0,index),Integer.parseInt(node.substring(index + 1))));
}
/* Jedis连接池配置 */
JedisPoolConfig jedisPoolConfig = getJedisPoolConfig();
return new JedisCluster(hostAndPorts,redisClusterProperties.getCommandTimeout(),jedisPoolConfig);
}
/**
* 连接池配置
* @return JedisPoolConfig
**/
private JedisPoolConfig getJedisPoolConfig(){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(redisPoolProperties.getMaxIdle()); // 最大空闲连接数, 默认8个
jedisPoolConfig.setMaxTotal(redisPoolProperties.getMaxActive()); // 最大连接数, 默认8个
jedisPoolConfig.setMinIdle(redisPoolProperties.getMinIdle()); // 最小空闲连接数, 默认0
jedisPoolConfig.setMaxWaitMillis(redisPoolProperties.getMaxWait()); // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
jedisPoolConfig.setTestOnBorrow(true); // 对拿到的connection进行validateObject校验
return jedisPoolConfig;
}
}
获取redis客户端
新增一个工具接口IRedisCluster,然后写一个组件对接口进行实现:获取redis客户端实例后,进行redis相关操作的封装
接口
public interface IRedisCluster {
String set(String key, String value);
String get(String key);
}
实现IRedisCluster接口
@Service("redisClusterService")
public class RedisClusterService implements IRedisCluster{
@Autowired
private JedisCluster jedisCluster;
@Override
public String set(String key, String value) {
return jedisCluster.set(key, value);
}
@Override
public String get(String key) {
return jedisCluster.get(key);
}
}
先封装两个最简单的方法,更详细的封装后续再介绍
使用
新增一个RedisController编写简单的服务接口:
@RestController
public class RedisClusterController {
@Autowired
@Qualifier("redisClusterService")
private IRedisCluster redisCluster;
@PostMapping("/cluster/jedis/{key}")
public void setDataByJedis(@PathVariable("key") String key){
System.out.println("set " + key);
redisCluster.set(key,key + "nice");
}
@GetMapping("/cluster/jedis/{key}")
public void getDataByJedis(@PathVariable("key") String key){
System.out.println(redisCluster.get(key));
}
}
验证
用postman分别调用setData和getData对应服务,控制台打印以下信息:

用redis-cli客户端连接集群中任意一个节点
redis-cli -c -p 7001
得到集群中已经有相关记录:

集成spring-data-redis
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置绑定
因为是Spring封装的组件,所以有比较完善的支持,我们直接在``下新增关于集群的配置
# ------------------------------------------------------------ cluster集群模式
# 重连最大数
spring.redis.cluster.max-redirects=3
# 集群主机信息
spring.redis.cluster.nodes=127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005,127.0.0.1:7006
# ------------------------------------------------------------ 连接池配置
# lettuce
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.min-idle=0
- 配置spring.redis.lettuce.pool节点会自动你开启连接池
- 需将单机模式的相关配置注释掉,不然虽然能启动,但的操作redis时会报错
注册
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
/* 设置value的序列化规则和 key的序列化规则 */
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer); // key采用String的序列化方式
redisTemplate.setHashKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式
redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer); // value序列化方式采用jackson
redisTemplate.setConnectionFactory(connectionFactory); // 默认使用letttuce,如果想使用Jedis,创建JedisConnectionFactory实例作为参数传入
return redisTemplate;
}
}
获取redis客户端
同样实现的上述的IRedisCluster接口
@Service("redisClusterTemplateService")
public class RedisClusterTemplateService implements IRedisCluster{
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Override
public String set(String key, String value) {
redisTemplate.opsForValue().set(key,value);
return key;
}
@Override
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
}
使用
编写对应的set和get服务
@RestController
public class RedisClusterController {
@Autowired
@Qualifier("redisClusterTemplateService")
private IRedisCluster redisTemplateCluster;
@PostMapping("/cluster/{key}")
public void setData(@PathVariable("key") String key){
System.out.println("set " + key);
redisTemplateCluster.set(key,key + " nice");
}
@GetMapping("/cluster/{key}")
public void getData(@PathVariable("key") String key){
System.out.println(redisTemplateCluster.get(key));
}
}
验证
用postman分别调用setData和getData对应服务,控制台打印以下信息:

用redis-cli客户端连接集群中任意一个节点
redis-cli -c -p 7006
得到集群中已经有相关记录:

异常处理
io.lettuce.core.RedisConnectionException: Connection closed prematurely
redis启动配置中默认是有保护模式的,要关闭保护模式
Spring Boot集成Redis集群(Cluster模式)的更多相关文章
- redis集群cluster模式搭建
实验服务器 :192.168.44.139 192.168.44.138 192.168.44.144 在 192.168.44.139上操作: 将redis的包上传的新建的目录newtouc ...
- Redis集群-Cluster模式
我理解的此模式与哨兵模式根本区别: 哨兵模式采用主从复制模式,主和从数据都是一致的.全量数据: Cluster模式采用数据分片存储,对每个 key 计算 CRC16 值,然后对 16384 取模,可以 ...
- Springboot2.x集成Redis集群模式
Springboot2.x集成Redis集群模式 说明 Redis集群模式是Redis高可用方案的一种实现方式,通过集群模式可以实现Redis数据多处存储,以及自动的故障转移.如果想了解更多集群模式的 ...
- Spring集成Redis集群(含spring集成redis代码)
代码地址如下:http://www.demodashi.com/demo/11458.html 一.准备工作 安装 Redis 集群 安装参考: http://blog.csdn.net/zk6738 ...
- SpringBoot(十一): Spring Boot集成Redis
1.在 pom.xml 中配置相关的 jar 依赖: <!-- 加载 spring boot redis 包 --> <dependency> <groupId>o ...
- redis单点、redis主从、redis哨兵sentinel,redis集群cluster配置搭建与使用
目录 redis单点.redis主从.redis哨兵 sentinel,redis集群cluster配置搭建与使用 1 .redis 安装及配置 1.1 redis 单点 1.1.2 在命令窗口操作r ...
- Docker快速构建Redis集群(cluster)
Docker快速构建Redis集群(cluster) 以所有redis实例运行在同一台宿主机上为例子 搭建步骤 redis集群目录清单 . ├── Dockerfile ├── make_master ...
- Spring Boot 2.X(六):Spring Boot 集成Redis
Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...
- springmvc3.2集成redis集群
老项目需要集成redis集群 因为spring版本才从2.x升级上来,再升级可能改动较大,且并非maven项目升级麻烦,故直接集成. jar包准备: jedis-2.9.0.jar -- 据说只有这 ...
随机推荐
- python的setup.py文件及其常用命令
编写setup.py文件,获取帮助:python setup.py --help-commands [python] Standard commands: build ...
- PAT甲级:1064 Complete Binary Search Tree (30分)
PAT甲级:1064 Complete Binary Search Tree (30分) 题干 A Binary Search Tree (BST) is recursively defined as ...
- P4180 [BJWC2010]严格次小生成树
P4180 [BJWC2010]严格次小生成树 P4180 题意 求出一个无向联通图的严格次小生成树.严格次小生成树的定义为边权和大于最小生成树的边权和但不存在另一棵生成树的边权和在最小生成树和严格次 ...
- SAML 2.0 实例分析 idp向sp发送响应(4)
当idp与user建立起联系后,idp向sp发送响应 <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol ...
- vant vue 屏幕自适应
手机端 pc端 屏幕自适应 一.新建 vue.config.js项目目录中没有 vue.config.js 文件,需要手动创建,在根目录中创建 vue.config.js const pxtorem ...
- HashSet 的实现原理
HashSet 概述 对于 HashSet 而言,它是基于 HashMap 实现的,底层采用 HashMap 来保存元素,所以如果对 HashMap 比较熟悉了,那么学习 HashSet 也是很轻松的 ...
- jstack 命令使用经验总结
jstack 命令的基本使用 jstack 在命令使用上十分简洁, 其信息量与复杂度主要体如今 thread dump 内容的分析上;web # 最基本的使用sudo -u xxx jstack {v ...
- 论文笔记:(2017NIPS)DeepSets
目录 摘要 一.引言 二.置换不变性和等变性 2.1 问题定义 2.2 结构 2.3 相关结果 三.Deep Sets 3.1 架构 3.2 其他相关工作 四.应用和实验结果 4.1 设置输入标量响应 ...
- Jquery遍历复选框选中项
var ret=''; $('name=chkIds').each(function(){ if($(this).is(':checked')){ ret+=$(this).val()+','; } ...
- 为什么说使用 Linux 系统学习 OpenGL 更方便
前言 上一篇随笔介绍了我的电脑,同时也介绍了 Ubuntu 20.10 系统的安装和美化.这一篇,我将正式开始 OpenGL 之旅.使用 Ubuntu 来进行开发,不仅仅只是因为我对 Linux 桌面 ...