前言:在上一文中,我講到了---如何搭建redis集群---讓集群擁有分片的數(shù)據(jù)內(nèi)存的擴容和哨兵的高可用。今天給大家講解一下Spring如何整合Redis集群
在這里首先給大家說一說分片和哨兵的特點:
- 1.分片的主要的作用 實現(xiàn)內(nèi)存數(shù)據(jù)的擴容
- 2.哨兵主要的作用,可以實現(xiàn)redis的高可用.
- 3.如果redis分片中有一個redis節(jié)點宕機,則整個redis分片將不能正常運行.
- 4.Redis哨兵雖然可以實現(xiàn)Redis的高可用,但是哨兵本身沒辦法實現(xiàn)高可用,程序調(diào)用存在風險.
而集群確包含了分片和哨兵的兩者的優(yōu)點,既實現(xiàn)了內(nèi)存數(shù)據(jù)的擴容,也實現(xiàn)了redis的高可用,而且集群確保了一個或一定數(shù)量的redis宕機,也能夠讓程序正常的運行,這也是為什么我們運用的集群,而不是分片或哨兵。
???????????--------廢話有點多啊,下面進入今天的主題
1.Spring整合Redis集群
1.1在linux系統(tǒng)上開啟redis集群 --- sh start.sh
之后ps -ef |grep redis 檢測所有的redis服務器是否開啟

在這里插入圖片描述
1.2添加redis依賴(如若之前添加了,跳過此)
<!--spring整合redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
1.3redis集群測試實例
@Test
public void testCluster() {
Set<HostAndPort> nodes = new HashSet<HostAndPort>();
nodes.add(new HostAndPort("192.168.126.166",7000));
nodes.add(new HostAndPort("192.168.126.166",7001));
nodes.add(new HostAndPort("192.168.126.166",7002));
nodes.add(new HostAndPort("192.168.126.166",7003));
nodes.add(new HostAndPort("192.168.126.166",7004));
nodes.add(new HostAndPort("192.168.126.166",7005));
JedisCluster jedisCluster = new JedisCluster(nodes);
jedisCluster.set("redisCluster","集群測試");
System.out.println(jedisCluster.get("redisCluster"));
}
測試結(jié)果如下:
在這里插入圖片描述
測試成功?。?!
1.4編輯redis.properties文件
#標識IP地址和端口號信息 IP:PORT
redis.node=192.168.126.166:6379
redis.nodes=192.168.126.166:6379,192.168.126.166:6380,192.168.126.166:6381
redis.sentinel=192.168.126.166:26379
redis.cluster=192.168.126.166:7000,192.168.126.166:7001,192.168.126.166:7002,192.168.126.166:7003,192.168.126.166:7004,192.168.126.166:7005
1.5編輯redis配置類
//標識配置類
@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class JedisConfig {
//集群
@Value("${redis.cluster}")
private String nodes;
@Bean
public JedisCluster jedisCluster() {
Set<HostAndPort> nodeSet = new HashSet<HostAndPort>();
String[] nodeArray = nodes.split(",");
for(String node : nodeArray) {//node=host:port
String host = node.split(":")[0];
int port = Integer.parseInt(node.split(":")[1]);
HostAndPort hostAndPort = new HostAndPort(host,port);
nodeSet.add(hostAndPort);
}
return new JedisCluster(nodeSet);
}
}
1.6修改RedisAOP配置

在這里插入圖片描述
最后進行測試,測試成功,那就Spring整合Redis集群成功!??!
3月25日改:
有朋友發(fā)私信問我該如何去測試,其實這個很簡單。
你可以先查詢那幾臺服務器中哪些是主機,然后宕掉其中的一臺redis-cli -p 7000 shutdown,再十秒之后再去訪問頁面(在此之前你可以去看看7000主機的從機,現(xiàn)在是否是主機的了--redis-cli -p 7003>>>再輸入info replication),

image
如果能夠正常的訪問,說明
你整合Redis集群成功了,可以正常運行??!
如若你還有什么問題評論私信皆可?。?!