方法一:使用jedis客户端
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
二、配置application.properties或者application.yml(这里是yml)
spring:
redis:
cache.clusterNodes: 127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384,127.0.0.1:6385
cache.commandTimeout: 5000
三、创建RedisProperties对象,将application.yml文件中的信息赋值到RedisProperties对象中
package com.lld.alltest.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author: lld
* @Description:读取redis配置信息并装载
* @Date: Create in 2021 7/28 14:45
*/
@Component
@ConfigurationProperties(prefix = "spring.redis.cache")
public class RedisProperties {
private int expireSeconds;
private String clusterNodes;
private int commandTimeout;
public int getExpireSeconds() {
return expireSeconds;
}
public void setExpireSeconds(int expireSeconds) {
this.expireSeconds = expireSeconds;
}
public String getClusterNodes() {
return clusterNodes;
}
public void setClusterNodes(String clusterNodes) {
this.clusterNodes = clusterNodes;
}
public int getCommandTimeout() {
return commandTimeout;
}
public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}
}
四、创建JedisClusterConfig类解析RedisProperties对象的数据
package com.lld.alltest.config;
import com.lld.alltest.pojo.RedisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import java.util.HashSet;
import java.util.Set;
/**
* @Author: lld
* @Description:
* @Date: Create in 2021/7/28 15:02
*/
@Component
public class JedisClusterConfig {
@Autowired
private RedisProperties redisProperties;
public JedisCluster getJedisCluster(){
String [] serverArray=redisProperties.getClusterNodes().split(",");
Set<HostAndPort> nodes=new HashSet<>();
for (String ipPort:serverArray){
String [] ipPortPair=ipPort.split(":");
nodes.add(new HostAndPort(ipPortPair[0].trim(),Integer.valueOf(ipPortPair[1].trim())));
}
return new JedisCluster(nodes,redisProperties.getCommandTimeout());
}
}
五、测试使用
@SpringBootTest
class AlltestApplicationTests {
@Autowired
JedisClusterConfig jedisClusterConfig;
@Test
void stringRedisTest() {
jedisClusterConfig.getJedisCluster().set("bao","zst");
}
}
六、测试结果