The last article described how to set up a Redis cluster. Now let’s set up a client to connect to the Redis cluster and use it to operate the Redis cluster. Previous article: Setting up a Redis cluster – Super detailed configuration

1. Initialize a SpringBoot project

https://start.spring.io
Copy the code

2. Add a dependency to pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.1.6. RELEASE</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
Copy the code

3. Configure application.yml

jedis:
  cluster:
    nodes: 192.168.1.1:6379, 192.168.1.2:6379, 192.168.1.3:6379, 192.168.1.4:6379, 192.168.1.5:6379, 192.168.1.6:6379
    timeout: 3000
    pool:
      max-total: 800
      max-idle: 100
      min-idle: 50
      block-when-exhausted: true
      max-wait-millis: 1500
      test-on-borrow: false
      test-on-return: false
      test-while-idle: true
      time-between-eviction-runs-millis: 30000
      min_evictable_idle_time_millis: 1860000
      num_tests_per_eviction_run: 4
Copy the code

4. Write RedisClusterProperty. Java

@Configuration
@ConfigurationProperties(prefix = "jedis.cluster")
public class RedisClusterProperty {

    /** * Node list */
    private List<String> nodes;

    /** * Connection expiration time */
    private Integer timeout;
}
Copy the code

5. Write RedisClusterPoolProperty. Java

@Configuration
@ConfigurationProperties(prefix = "jedis.cluster.pool")
public class RedisClusterPoolProperty {

    /** * The maximum number of connections in the pool depends on the number of concurrent requests ** If the average time of a command is 10ms and the number of concurrent requests can be 100 times per second, maxTotal = 1000/100 = 10 */
    private Integer maxTotal;

    /** * The pool can have a maximum of several free connections ** This value is set to the same value as maxTotal, preventing maxTotal and maxTotal from creating and destroying connections too frequently */
    private Integer maxIdle;

    /** * The minimum number of free connections in the pool */
    private Integer minIdle;

    /** * Wait */ when no connection is available in the pool
    private Boolean blockWhenExhausted;

    /** * How long can you wait when no connections are available in the pool */
    private Integer maxWaitMillis;

    /** * Check whether a connection is available when a connection is fetched from the pool (ping) * Set to false */ is recommended
    private Boolean testOnBorrow;

    /** * Check whether the connection is available when it is returned to the pool (ping) * Set to false */ is recommended
    private Boolean testOnReturn;

    /** * Whether to enable idle connection detection * You are advised to set this parameter to true */
    private Boolean testWhileIdle;

    /** * Detection interval of idle resources */
    private Integer timeBetweenEvictionRunsMillis;

    /** * The minimum idle time of resources in the resource pool. After this value is reached, idle resources are removed for 30 minutes */
    private Long minEvictableIdleTimeMillis;

    /** * The default number of samples for idle resource detection is 3 */
    private Integer numTestsPerEvictionRun;

    /** * Build GenericObjectPoolConfig */
    @Bean
    public GenericObjectPoolConfig getGenericObjectPoolConfig(a) {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setBlockWhenExhausted(blockWhenExhausted);
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        poolConfig.setTestOnBorrow(testOnBorrow);
        poolConfig.setTestOnReturn(testOnReturn);
        poolConfig.setTestWhileIdle(testWhileIdle);
        poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        poolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        poolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        returnpoolConfig; }}Copy the code

6. Write RedisService. Java

@Service
public class RedisService {

    /** * redis cluster node parameters */
    private RedisClusterProperty redisClusterProperty;

    /** * Connection pool configuration file */
    private GenericObjectPoolConfig poolConfig;

    private JedisCluster jedisCluster;

    private Jedis jedis;

    /** * constructor *@paramRedisClusterProperty Redis Cluster node parameters *@paramPoolConfig connection pool configuration file */
    public RedisService(RedisClusterProperty redisClusterProperty, GenericObjectPoolConfig poolConfig) {
        this.redisClusterProperty = redisClusterProperty;
        this.poolConfig = poolConfig;
    }

    /** * Initialization method */
    @PostConstruct
    public void init(a) {

        Set<HostAndPort> hostAndPorts = new HashSet<>();

        List<String> nodes = redisClusterProperty.getNodes();
    
        if (CollectionUtils.isNotEmpty(nodes)) {
            if (nodes.size() == 1) {
                String[] hostAndPostStr = nodes.get(0).split(":");
                if (StringUtils.isNotBlank(hostAndPostStr[0]) && StringUtils.isNotBlank(hostAndPostStr[1])) {
                    jedis = new Jedis(hostAndPostStr[0], Integer.parseInt(hostAndPostStr[1])); }}else {
                for (String node : nodes) {
                    if (StringUtils.contains(node, ":")) {
                        String[] hostAndPostStr = node.split(":");
                        if (StringUtils.isNotBlank(hostAndPostStr[0]) && StringUtils.isNotBlank(hostAndPostStr[1])) {
                            hostAndPorts.add(new HostAndPort(hostAndPostStr[0], Integer.parseInt(hostAndPostStr[1))); }}}}this.jedisCluster = newJedisCluster(hostAndPorts, redisClusterProperty.getTimeout(), poolConfig); }}/** * Redis cluster configuration */
    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(a) {

        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();

        List<String> nodes = redisClusterProperty.getNodes();

        if (CollectionUtils.isNotEmpty(nodes)) {
            for (String node : nodes) {
                if (StringUtils.contains(node, ":")) {
                    String[] hostAndPostStr = node.split(":");
                    redisClusterConfiguration.addClusterNode(new RedisClusterNode(hostAndPostStr[0], Integer.parseInt(hostAndPostStr[1))); }}}return redisClusterConfiguration;
    }
    
    /** * String: Obtain * time complexity: O(1) */
    public String get(String key) {
        returnjedisCluster.get(key); }}Copy the code

7. Use RedisService to connect to the Redis cluster

@Service
public class TestService {
    
    @Autowired
    private RedisService redisService;
    
    public String get(String key) {
        returnredisService.get(key); }}Copy the code