引入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:
sentinel:
port: 26379
master: mymaster
nodes:
- 172.23.64.229
- 172.23.14.224
- 172.23.209.85
- 172.23.151.215
- 172.23.146.175
- 172.23.115.12
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);
}
}