SpringBoot整合Jedis可切换使用单机、哨兵、集群模式
admin
2024-01-19 11:29:02
0

前言

关于Redis的哨兵环境以及集群环境的搭建过程,可移步这里:

RedisCluster环境搭建https://blog.csdn.net/u014398573/article/details/127671087

Redis哨兵环境搭建https://blog.csdn.net/u014398573/article/details/127671023

话不多说,直接上代码吧,关注微信公众号: 【走进Java】 一起学习与交流!

1.Jedis依赖

redis.clientsjedis3.7.1

2.SpringBoot配置文件,关于Redis的内容

# redis
spring.redis.database=0
spring.redis.host=192.168.50.130
spring.redis.port=6379
spring.redis.password=enginex123
#连接超时时间(毫秒)
spring.redis.timeout=6000
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=3000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=1000
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=100
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=5
# 集群模式配置#最大重定向次数
spring.redis.cluster.max-redirects=5#集群节点列表
spring.redis.cluster.nodes=192.168.0.10:6380,192.168.0.10:6381,192.168.0.10:6382,192.168.0.11:6380,192.168.0.11:6381,192.168.0.11:6382# 哨兵模式配置#哨兵服务的密码,可能与redis本身密码是不用的,具体在sentinel配置文件里配置
spring.redis.sentinel.password=enginex123#主节点名称
spring.redis.sentinel.master=masterRedis#Sentinel节点列表
spring.redis.sentinel.nodes=192.168.50.130:26379
#redis环境模式 standalone:单机  cluster:集群 sentinel:哨兵
redis.model = sentinel

3.读取Redis配置属性类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;import java.util.List;/*** @author lisw* 微信公众号 ,走进Java* @description redis配置* @createDate 2022-11-01 16:23:40**/
@Data
@Configuration
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {private String host;private Integer port;private String password;private Integer database;private int timeout;private Cluster cluster;private Sentinel sentinel;public static class Cluster {private List nodes;private Integer maxRedirects;public List getNodes() {return nodes;}public void setNodes(List nodes) {this.nodes = nodes;}public Integer getMaxRedirects() {return maxRedirects;}public void setMaxRedirects(Integer maxRedirects) {this.maxRedirects = maxRedirects;}}public static class Sentinel{private List nodes;private String master;private String password;public List getNodes() {return nodes;}public void setNodes(List nodes) {this.nodes = nodes;}public String getMaster() {return master;}public void setMaster(String master) {this.master = master;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
}

4.读取Jedis配置属性

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;/*** @author lisw* 微信公众号 ,走进Java* @description redis配置* @createDate 2022-11-01 16:26:16**/
@Data
@Configuration
@Component
@ConfigurationProperties(prefix = "spring.redis.jedis.pool")
public class JedisProperties {private Integer maxIdle;private Integer maxWait;private Integer minIdle;private Integer maxActive;
}

5.Jedis 三种模式的Bean注入

SpringBoot,Jedis Bean注入,通过配置文件里面的redis.model属性决定使用什么模式,注入什么Bean,利用@ConditionalOnProperty注解

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.*;import java.util.HashSet;
import java.util.Set;/*** @author lisw* 微信公众号 ,走进Java* @description Redis Bean* @createDate 2022-11-01 16:27:56**/
@Configuration
public class RedisConfig {@Autowiredprivate RedisProperties redisProperties;@Autowiredprivate JedisProperties jedisProperties;@ConditionalOnProperty(value = "redis.model",havingValue = "standalone",matchIfMissing = true)@Beanpublic JedisPool redisPoolFactory() {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxIdle(jedisProperties.getMaxIdle());jedisPoolConfig.setMaxWaitMillis(jedisProperties.getMaxWait());if (StringUtils.isNotBlank(redisProperties.getPassword())) {return new JedisPool(jedisPoolConfig, redisProperties.getHost(), redisProperties.getPort(), redisProperties.getTimeout(), redisProperties.getPassword(), redisProperties.getDatabase());} else {return new JedisPool(jedisPoolConfig, redisProperties.getHost(), redisProperties.getPort(), redisProperties.getTimeout(), null, redisProperties.getDatabase());}}@ConditionalOnProperty(value = "redis.model",havingValue = "sentinel",matchIfMissing = false)@Beanpublic JedisSentinelPool jedisSentinelPool(){JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxIdle(jedisProperties.getMaxIdle());jedisPoolConfig.setMaxWaitMillis(jedisProperties.getMaxWait());// 截取集群节点String[] sentinels = redisProperties.getSentinel().getNodes().toArray(new String[0]);// 创建set集合Set nodes = new HashSet<>();// 循环数组把集群节点添加到set集合中for (String node : sentinels) {//添加节点nodes.add(node);}if(StringUtils.isNotBlank(redisProperties.getSentinel().getPassword())){return new JedisSentinelPool(redisProperties.getSentinel().getMaster(),nodes,jedisPoolConfig, redisProperties.getTimeout(),redisProperties.getTimeout(),redisProperties.getPassword(),redisProperties.getDatabase(),null,redisProperties.getTimeout(),redisProperties.getTimeout(),redisProperties.getSentinel().getPassword(),null);}else{return new JedisSentinelPool(redisProperties.getSentinel().getMaster(),nodes,jedisPoolConfig,redisProperties.getTimeout(),redisProperties.getPassword() );}}@ConditionalOnProperty(value = "redis.model",havingValue = "cluster",matchIfMissing = false)@Beanpublic JedisCluster getJedisCluster() {JedisPoolConfig poolConfig = new JedisPoolConfig();poolConfig.setMaxIdle(jedisProperties.getMaxIdle());poolConfig.setMaxWaitMillis(jedisProperties.getMaxWait());poolConfig.setMinIdle(jedisProperties.getMinIdle());poolConfig.setMaxTotal(jedisProperties.getMaxActive());// 截取集群节点String[] cluster = redisProperties.getCluster().getNodes().toArray(new String[0]);// 创建set集合Set nodes = new HashSet<>();// 循环数组把集群节点添加到set集合中for (String node : cluster) {String[] host = node.split(":");//添加集群节点nodes.add(new HostAndPort(host[0], Integer.parseInt(host[1])));}//需要密码连接的创建对象方式return new JedisCluster(nodes, redisProperties.getTimeout(), 2000, redisProperties.getCluster().getMaxRedirects(), redisProperties.getPassword(), poolConfig);}
}

6.定义对业务使用的RedisManager接口

业务上使用时通过RedisManager注入进行使用,三种模式只会注入一个进去。代码如下

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import com.fibo.ddp.common.utils.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.*;import java.util.*;public interface RedisManager {byte[] get(byte[] key);String get(String key);byte[] set(byte[] key, byte[] value);String set(String key, String value);byte[] set(byte[] key, byte[] value, int expire);String set(String key, String value, int expire);void del(byte[] key);void del(String key);}

7.RedisManage的集群模式实现

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import redis.clients.jedis.*;import java.util.*;/*** @author lisw* @program ddp-project* @description Redis管理器 集群模式* @createDate 2022-11-01 17:19:29**/
@Component
@ConditionalOnProperty(value = "redis.model",havingValue = "cluster",matchIfMissing = false)
@Slf4j
public class RedisManagerJedisCluster implements RedisManager{private int expire = 0;@Autowired(required = false)private JedisCluster jedisCluster;@Overridepublic byte[] get(byte[] key) {return jedisCluster.get(key);}@Overridepublic String get(String key) {return jedisCluster.get(key);}@Overridepublic byte[] set(byte[] key, byte[] value) {jedisCluster.set(key,value);if(this.expire!=0){jedisCluster.expire(key,expire);}return value;}@Overridepublic String set(String key, String value) {jedisCluster.set(key,value);if(this.expire!=0){jedisCluster.expire(key,expire);}return value;}@Overridepublic byte[] set(byte[] key, byte[] value, int expire) {jedisCluster.set(key,value);if(expire!=0){jedisCluster.expire(key,expire);}return value;}@Overridepublic String set(String key, String value, int expire) {jedisCluster.set(key,value);if(expire!=0){jedisCluster.expire(key,expire);}return value;}@Overridepublic void del(byte[] key) {jedisCluster.del(key);}@Overridepublic void del(String key) {jedisCluster.del(key);}
}

8.RedisManager的哨兵模式实现

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import redis.clients.jedis.*;import java.util.*;/*** @author lisw* @program ddp-project* @description Redis管理,哨兵模式实现* @createDate 2022-11-02 18:01:03**/
@Component
@ConditionalOnProperty(value = "redis.model",havingValue = "sentinel",matchIfMissing = false)
@Slf4j
public class RedisManagerJedisSentinel implements RedisManager{private int expire = 0;@Autowired(required = false)private JedisSentinelPool jedisPool;@Overridepublic byte[] get(byte[] key) {byte[] value = null;Jedis jedis =null;try {jedis = jedisPool.getResource();value = jedis.get(key);} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {jedis.close();//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic String get(String key) {String value = null;Jedis jedis = jedisPool.getResource();try {value = jedis.get(key);} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic byte[] set(byte[] key, byte[] value) {Jedis jedis = jedisPool.getResource();try {jedis.set(key, value);if (this.expire != 0) {jedis.expire(key, this.expire);}} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic String set(String key, String value) {Jedis jedis = jedisPool.getResource();try {jedis.set(key, value);if (this.expire != 0) {jedis.expire(key, this.expire);}} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic byte[] set(byte[] key, byte[] value, int expire) {Jedis jedis = null;try {jedis = jedisPool.getResource();jedis.set(key, value);if (expire != 0) {jedis.expire(key, expire);}} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic String set(String key, String value, int expire) {Jedis jedis = jedisPool.getResource();try {jedis.set(key, value);if (expire != 0) {jedis.expire(key, expire);}} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic void del(byte[] key) {Jedis jedis = jedisPool.getResource();try {jedis.del(key);} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}}@Overridepublic void del(String key) {Jedis jedis = jedisPool.getResource();try {jedis.del(key);} finally {if (jedis != null) {jedis.close();}}}}

9.RedisManager的单机模式实现

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import redis.clients.jedis.*;import java.util.*;/*** @author lisw* @program ddp-project* @description Redis管理,单机模式实现* @createDate 2022-11-01 17:09:01**/
@Component
@ConditionalOnProperty(value = "redis.model",havingValue = "standalone",matchIfMissing = true)
@Slf4j
public class RedisManagerJedisStandalone implements RedisManager {private int expire = 0;@Autowired(required = false)private JedisPool jedisPool;@Overridepublic byte[] get(byte[] key) {byte[] value = null;Jedis jedis =null;try {jedis = jedisPool.getResource();value = jedis.get(key);} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {jedis.close();//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic String get(String key) {String value = null;Jedis jedis = jedisPool.getResource();try {value = jedis.get(key);} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic byte[] set(byte[] key, byte[] value) {Jedis jedis = jedisPool.getResource();try {jedis.set(key, value);if (this.expire != 0) {jedis.expire(key, this.expire);}} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic String set(String key, String value) {Jedis jedis = jedisPool.getResource();try {jedis.set(key, value);if (this.expire != 0) {jedis.expire(key, this.expire);}} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic byte[] set(byte[] key, byte[] value, int expire) {Jedis jedis = null;try {jedis = jedisPool.getResource();jedis.set(key, value);if (expire != 0) {jedis.expire(key, expire);}} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic String set(String key, String value, int expire) {Jedis jedis = jedisPool.getResource();try {jedis.set(key, value);if (expire != 0) {jedis.expire(key, expire);}} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}return value;}@Overridepublic void del(byte[] key) {Jedis jedis = jedisPool.getResource();try {jedis.del(key);} catch (Exception e) {//释放redis对象jedisPool.returnBrokenResource(jedis);e.printStackTrace();} finally {//返还到连接池if (jedis != null) {jedisPool.returnResource(jedis);}}}@Overridepublic void del(String key) {Jedis jedis = jedisPool.getResource();try {jedis.del(key);} finally {if (jedis != null) {jedis.close();}}}}

10.业务代码注入RedisManager

@Autowired
private RedisManager redisManager;

11 最后

只需修改redis.model配置值就可以切换redis三种模式,值分别是:standalone,cluster,sentinel

相关内容

热门资讯

广东猪肠粉滑溜溜!酱油淋裹粉卷... 本文将全方位展现广东猪肠粉的独特魅力,从其在广东早餐界的重要地位入手,详细介绍猪肠粉的起源与发展、制...
原创 剧... 9月,一条消息如同一阵春风,吹遍了网络的每一个角落:“以前很火的电视剧都被做成了辣条外包装!”这波操...
原创 火... 火锅底料中的红油,是用什么油制成的? 在探讨火锅底料的奥秘时,我们不得不提的是那一抹诱人的红油。它...
妙可蓝多,如何把奶酪打造成生活... 8月22日,妙可蓝多官宣“奶酪坚果脆”全面登陆全国山姆门店,为奶酪消费市场注入全新活力。这款以奶酪为...
北京旅游最佳月份攻略揭秘:秋季... 导语:北京,这座历史与现代交融的国际大都市,四季分明,风光各异。那么,究竟哪个月份是前往北京旅游的最...
四川五天旅游计划及花费,和父母... 家人们,四川,那可是一片神奇而迷人的土地,宛如一颗镶嵌在祖国西南的璀璨明珠。它有着令人叹为观止的自然...
两摩托艇海上发生碰撞 三亚吉阳... 央广网三亚9月10日消息(记者 蔡文娟) 9月10日晚,三亚市吉阳区旅游工作领导小组办公室发布一则情...
原创 玉... 玉米面黑芝麻饼,手不沾面就能做,非常简单的快手小饼。 在忙碌的生活中,我们总是渴望能够快速制作出美...
原创 湘... 标题:湘菜馆四个人点七盘菜六百多,三盘虾就花了五百块 在湖南的某个小镇上,有一家闻名遐迩的湘菜馆。...
原创 世... 在这个世界上,有一种美食,它不仅承载着味觉的享受,更是一种艺术的展现。今天,我要与大家分享的,是世界...
原创 明... 明天农历七月二十一日,是福建松溪县的传统节日“游仙节”。相传该节日起源于明清时期,从七月廿十持续到七...
海南自贸港旅文推介会在香港举行...   9月10日,在香港K11艺术购物中心,一名香港博主向市民分享海南旅游心得。新华社发(王申 摄) ...
四川游玩6日游报价咨询,驴友亲... 嘿,各位热爱旅行的朋友们,今天我要跟大家分享一次难忘的四川之旅。这次旅行不仅让我领略了四川的壮丽山河...
那远山呼唤我,买锐界L不露营确... 8月再见,好像是露营三次,纯玩,自驾,享受生活; 9月你好,继续露营,只有户外,只有自然,那才是一份...
学生党到四川五日游纯玩线路,成... 宝子们,四川那可是一个集万千宠爱于一身的旅游胜地啊!它就像一幅绚丽多彩的画卷,在祖国的西南大地上徐徐...
丝娃娃 - 贵州美食的独特画卷 在贵州的美食天地里,丝娃娃宛如一幅色彩斑斓的独特画卷,以其别具一格的形态与丰富多元的口感,深深烙印在...
宠物出境游精选地推荐 携宠出行... 随着人们生活水平的提高,越来越多的家庭开始养宠物。宠物已经成为家庭中不可或缺的一员。而随着宠物数量的...
伦敦香蕉图爆火!专家:忘掉香蕉... 要问这几天伦敦讨论度最高的水果是什么?恐怕非香蕉莫属! 而这一切的起因,是一张在网上疯传的地图——“...
国庆游广东潮汕五日游要多少钱?... 十一假期,是许多人翘首以盼的出游黄金时段。在这个秋高气爽、风景宜人的时节,大家都渴望走出家门,去探寻...
【1024·关注】价格降了!有... 眼下正值国庆假期前的错峰游黄金窗口期。记者走访浙江宁波多家旅行社发现,当前各类旅游产品价格普遍下调,...