引入Maven依赖:
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
SpringBoot配置绑定
Spring封装的组件,比较完善的支持,我们直接在下新增关于集群的配置:
spring:
redis:
cluster:
nodes:
- 172.23.64.219:6379
- 172.23.151.213:6379
- 172.23.62.212:6379
- 172.23.115.12:6379
- 172.23.146.158:6379
- 172.23.14.247:6379
# 获取失败 最大重定向次数
max-redirects: 3
lettuce:
shutdown-timeout: 200ms
pool:
max-idle: 16
max-active: 32
min-idle: 8
调用测试:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.RedisClientInfo;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RedisTest {
@Autowired
private RedisTemplate<String, String> redisTemplate;
public List<RedisClientInfo> getClientList(String param) {
return redisTemplate.getClientList();
}
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
public void put(String k, String v) {
redisTemplate.opsForValue().set(k, v);
}
}