pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
我的项目中,spring boot是 用的2.1.8版本.
spring-boot-starter-redis在springboot 1.4.7版本后,
改为了spring-boot-starter-data-redis,
所以如果想集成redis,
应该引用spring-boot-starter-data-redis.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
yml
spring:
redis:
cache.clusterNodes: 127.0.0.1:6379,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
cache.commandTimeout: 5000
config
spring.redis.cache.clusterNodes=127.0.0.1:6379,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
spring.redis.cache.commandTimeout=5000
package com.sdyy.springboot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import java.util.HashSet;
import java.util.Set;
/**
*
* * @className: JedisClusterConfig
*
* @description TODO
* * @param
* * @return
* * @throws
* * @author lizz
* * @date 2020 02 18 14:47
*
*/
@Configuration
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());
}
}
package com.sdyy.springboot.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
*
* * @className: RedisProperties
*
* @description TODO
* * @param
* * @return
* * @throws
* * @author lizz
* * @date 2020 02 18 14:41
*
*/
@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;
}
}
参考
https://blog.csdn.net/u010199866/article/details/80705797