Use JedisCluster to operate the Redis cluster List in Spring Boot microservices

Records : 450

Scenario : Use JedisCluster in the Spring Boot microservice to operate the List list data type of the Redis cluster. 

Versions : JDK 1.8, Spring Boot 2.6.3, redis-6.2.5, jedis-3.7.1.

1. Configure Redis information in microservices

1.1 Add dependencies in pom.xml

pom.xml file:

<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>3.7.1</version>
</dependency>

Analysis: jedis is integrated by default in Spring Boot, and there is no need to add a version number to use it. Version 3.7.1 in this example is the version corresponding to Spring Boot 2.6.3.

1.2 Configure Redis cluster information in application.yml

(1) application.yml configuration content

hub:
  example:
    redis:
      jedis-cluster:
        password: demo12345678
        connection-timeout: 60000
        so-timeout: 1000
        max-attempts: 100
        nodes:
          - 192.168.19.161:27001
          - 192.168.19.161:27002
          - 192.168.19.162:27001
          - 192.168.19.162:27002
          - 192.168.19.163:27001
          - 192.168.19.163:27002

(2) Analysis

The configuration content in application.yml is customized, corresponding to the custom configuration class JedisClusterProperties.

Full class name: com.hub.example.config.JedisClusterProperties.

Custom configuration classes use the following annotations to take effect:

@ConfigurationProperties(prefix = "hub.example.redis.jedis-cluster")

1.3 Load brief logic

When the Spring Boot microservice starts, the automatic annotation mechanism will read the configuration information of application.yml and inject it into the corresponding properties of the custom configuration class JedisClusterProperties object. Therefore, the configuration information of the Redis cluster can be obtained in the Spring environment.

Spring takes the configuration from the JedisClusterProperties object and injects it into the JedisCluster client. Therefore, the JedisCluster client can perform operations such as addition, deletion, modification, and query on the Redis cluster.

2. Configure JedisCluster

JedisCluster is a Redis client encapsulated in the jedis framework.

Full class name: redis.clients.jedis.JedisCluster

2.1 Configure JedisClusterProperties

JedisClusterProperties is a custom configuration that loads the configuration information of the Redis cluster in application.yml.

Use the @ConfigurationProperties annotation to take effect, and use the prefix of the annotation to specify the prefix in the configuration application.yml.

@Component
@ConfigurationProperties(prefix = "hub.example.redis.jedis-cluster")
public class JedisClusterProperties {
  private List<String> nodes;
  private String password;
  private int connectionTimeout;
  private int soTimeout;
  private int maxAttempts;
  public List<String> getNodes() {
      return nodes;
  }
  public void setNodes(List<String> nodes) {
      this.nodes = nodes;
  }
  public String getPassword() {
      return password;
  }
  public void setPassword(String password) {
      this.password = password;
  }
  public int getConnectionTimeout() {
      return connectionTimeout;
  }
  public void setConnectionTimeout(int connectionTimeout) {
      this.connectionTimeout = connectionTimeout;
  }
  public int getSoTimeout() {
      return soTimeout;
  }
  public void setSoTimeout(int soTimeout) {
      this.soTimeout = soTimeout;
  }
  public int getMaxAttempts() {
      return maxAttempts;
  }
  public void setMaxAttempts(int maxAttempts) {
      this.maxAttempts = maxAttempts;
  }
}

2.2 Configure JedisCluster

@Configuration
public class JedisClusterConfig {
  @Autowired
  JedisClusterProperties jedisClusterProperties;
  @Bean("jedisCluster")
  public JedisCluster getJedisCluster(JedisPoolConfig jedisPoolConfigCluster) {
    List<String> nodesList = jedisClusterProperties.getNodes();
    Set<HostAndPort> nodesSet = new HashSet<>();
    for (String ipAndPort : nodesList) {
        String[] ipAndPortPair = ipAndPort.split(":");
        nodesSet.add(new HostAndPort(ipAndPortPair[0].trim(), Integer.parseInt(ipAndPortPair[1].trim())));
    }
  
    return new JedisCluster(nodesSet,
            jedisClusterProperties.getConnectionTimeout(),
            jedisClusterProperties.getSoTimeout(),
            jedisClusterProperties.getMaxAttempts(),
            jedisClusterProperties.getPassword(),
            jedisPoolConfigCluster
    );
  }
  @Bean("jedisPoolConfigCluster")
  public JedisPoolConfig jedisPoolConfigCluster() {
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    jedisPoolConfig.setMaxTotal(30);
    jedisPoolConfig.setMaxIdle(30);
    jedisPoolConfig.setMinIdle(1);
    jedisPoolConfig.setNumTestsPerEvictionRun(-1);
    jedisPoolConfig.setTestOnBorrow(true);
    jedisPoolConfig.setTestOnReturn(false);
    jedisPoolConfig.setBlockWhenExhausted(false);
    return jedisPoolConfig;
  }
}

2.3 Analysis

After configuring JedisCluster, in the Spring environment, use the @Autowired annotation to inject the JedisCluster instance to operate the Redis cluster.

3. Use Jedis to operate the Redis cluster List list

3.1 Brief description

Use JedisCluster to operate the cluster List list, common operations: add, check, modify, delete, set timeout, etc.

3.2 Operation example

@RestController
@RequestMapping("/hub/example/operateJedisCluster")
@Slf4j
public class OperateJedisClusterController {
  @Autowired
  private JedisCluster jedisCluster;
  /**
   * 使用JedisCluster操作Redis集群List列表类型数据
   */
  @GetMapping("/f03")
  public Object f03() {
      log.info("JedisCluster操作Redis集群开始...");
      // 1.增
      // 1.1写入一条数据到队列,队列名称,队列值
      jedisCluster.rpush("J:2023060803:01", "苏州-姑苏");
      jedisCluster.lpush("J:2023060803:01", "苏州-工业园区");
      // 1.2写入批量数据到队列
      jedisCluster.rpush("J:2023060803:01", "苏州-工业园区"
              , "苏州-昆山", "苏州-相城", "苏州-吴江");
      // 2.查
      // 2.1从队列中取值,队列值取出后,队列中就没值了
      String city01 = jedisCluster.lpop("J:2023060803:01");
      String city02 = jedisCluster.rpop("J:2023060803:01");
      // 2.2查询队列长度
      Long len = jedisCluster.llen("J:2023060803:01");
      // 2.3获取指定范围的值,不会修改队列值
      List<String> list = jedisCluster.lrange("J:2023060803:01", 2, 4);
      // 3.删
      long time = 8000;
      log.info("{}秒后,删除J:2023060803:01.", time / 1000);
      ThreadUtil.sleep(time);
      jedisCluster.del("J:2023060803:01");
      // 4.设置超时
      jedisCluster.rpush("J:2023060803:02", "苏州-姑苏");
      jedisCluster.expire("J:2023060803:02", 600L);
      log.info("JedisCluster操作Redis集群结束...");
      return "执行成功";
  }
}

3.3 Test verification

Use Postman test.

Request RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/operateJedisCluster/f03

Above, thanks.

June 8, 2023

Guess you like

Origin blog.csdn.net/zhangbeizhen18/article/details/131115409