pom.xml添加依赖包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis单机版和集群版的application.properties文件配置区别:
1.单机版配置:
#------------(单机版配置)
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6380
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000
spring.redis.commandTimeout=5000
spring.redis.testOnBorrow=false
2.集群版配置:
#------------(集群版配置)
#redis集群(cluster集群)
spring.redis.cluster.nodes=127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382
spring.redis.cluster.timeout=5
spring.redis.cluster.max-redirects=3
spring.redis.cluster.password=
3.测试集群:
package com.wyq.springBoot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTests {
@Autowired
RedisTemplate<String, String> strRedisTpl;
//集群版配置的测试
@Test
public void testCluster() throws InterruptedException{
String key = "springBoot.redis.test.keyc__";
for (int i = 0; i < 50; i++) {
strRedisTpl.opsForValue().set(key+i, "hello redis==."+i);
System.out.println(strRedisTpl.opsForValue().get(key+i));
}
Thread.sleep(5000);
System.out.println("===================开始取");
for (int i = 0; i < 50; i++) {
System.out.println(strRedisTpl.opsForValue().get(key+i));
}
}
}
运行之后,可看到,50个key-value,会被redis Cluster根据键到槽(slot)的基本映射算法(Redis Cluster分区实现原理),分别把数据存在我们配置的3个节点中(127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382):
Tips:windows配置redis集群方法,可参考我的博文《springBoot学习篇》(3)Windows下配置Redis集群