pom文件
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
properties配置文件
redis.hosts=192.168.139.129:7001,192.168.139.129:7002,192.168.139.129:7003,192.168.139.129:7004,192.168.139.129:7005,192.168.139.129:7006
配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Configuration
@PropertySource("classpath:redis.properties")
public class RedisJqConfig {
@Value("#{'${redis.hosts}'.split(',')}")
private List<String> hosts;
@Bean
public JedisPoolConfig JedisPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(30);//最大连接数
config.setMaxIdle(10);//最大空闲连接数
config.setTimeBetweenEvictionRunsMillis(3000);
config.setMaxWaitMillis(1500);
config.setTestOnBorrow(true);
config.setTestWhileIdle(true);
config.setBlockWhenExhausted(false);
return config;
}
@Bean
public Set<HostAndPort> hosts() {
Set<HostAndPort> set = new HashSet<HostAndPort>();
for (String host: hosts) {
String[] split = host.split(":");
HostAndPort port = new HostAndPort(split[0],Integer.parseInt(split [1]));
set.add(port);
}
return set;
}
@Bean
public JedisCluster jedisCluster() {
JedisCluster cluster = new JedisCluster(hosts(),JedisPoolConfig());
return cluster;
}
}
测试类
import com.dengying.config.RedisJqConfig;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import redis.clients.jedis.JedisCluster;
public class JedisJq {
private ApplicationContext applicationContext;
@Before
public void before() {
applicationContext = new AnnotationConfigApplicationContext(RedisJqConfig.class);
}
@Test
public void test() {
JedisCluster jedisCluster = (JedisCluster) applicationContext.getBean("jedisCluster");
jedisCluster.set("name", "zhangsan");
String value = jedisCluster.get("name");
System.out.println(value);
}
}