Use HashOperations to operate Redis cluster Hash in Spring Boot microservices

Records : 445

Scenario : Use HashOperations of RedisTemplate in Spring Boot microservices to operate the Hash hash data type of Redis cluster.

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

1. Configure Redis information in microservices

1.1 Add dependencies in pom.xml

pom.xml file:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
  <version>2.6.3</version>
</dependency>

Analysis: spring-boot-starter-data-redis and spring-boot versions are consistent.

1.2 Configure Redis cluster information in application.yml

(1) application.yml configuration content

spring:
  redis:
    cluster:
      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
    password: demo12345678
    timeout: 60000

(2) Analysis

Configure content sources.

jar包:spring-boot-autoconfigure-2.6.3.jar。

类:org.springframework.boot.autoconfigure.data.redis.RedisProperties。

This package was already introduced when spring-boot-starter was introduced.

When you need to configure other information of the cluster, you can find it in the RedisProperties class and configure it in application.yml to take effect.

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 RedisProperties object. Therefore, the configuration information of the Redis cluster can be obtained in the Spring environment.

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

2. Configure RedisTemplate

RedisTemplate is a client for operating Redis encapsulated in the springframework framework.

Full class name: org.springframework.data.redis.core.RedisTemplate

2.1 Configure RedisTemplate

@Configuration
public class RedisConfig {
  @Bean("redisTemplate")
  public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
      // 1.创建RedisTemplate对象
      RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
      // 2.加载Redis配置
      redisTemplate.setConnectionFactory(lettuceConnectionFactory);
      // 3.配置key序列化
      RedisSerializer<?> stringRedisSerializer = new StringRedisSerializer();
      redisTemplate.setKeySerializer(stringRedisSerializer);
      redisTemplate.setHashKeySerializer(stringRedisSerializer);
      // 4.配置Value序列化
      Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
      ObjectMapper objMapper = new ObjectMapper();
      objMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      objMapper.activateDefaultTyping(objMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
      jackson2JsonRedisSerializer.setObjectMapper(objMapper);
      redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
      redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
      // 5.初始化RedisTemplate
      redisTemplate.afterPropertiesSet();
      return redisTemplate;
  }
  @Bean
  public HashOperations<String, Object, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
      return redisTemplate.opsForHash();
  }
}

2.2 Analysis

After using @Configuration and @Bean to configure RedisTemplate, use @Autowired annotation to inject RedisTemplate and HashOperations instances to operate Redis cluster.

3. Use HashOperations to operate Redis cluster Hash hash

3.1 Brief description

Use ValueOperations to manipulate strings, common operations: add, check, modify, delete, set timeout, etc.

3.2 Operation example

@RestController
@RequestMapping("/hub/example/operateCluster")
@Slf4j
public class OperateClusterController {
  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private HashOperations hashOperations;
  /**
   * 使用HashOperations,操作Hash类型数据
   */
  @GetMapping("/f04")
  public Object f04() {
      log.info("HashOperations操作Redis集群开始...");
      // 1.增
      hashOperations.put("D:2023060804:01", "hangzhou", "杭州");
      hashOperations.put("D:2023060804:01", "suzhou", "苏州");
      hashOperations.put("D:2023060804:01", "nanjing", "南京");
      // 2.1查-获取map键值对数据
      Map resultMap = hashOperations.entries("D:2023060804:01");
      resultMap.forEach((key, value) -> {
          System.out.println("key=" + key + ",value=" + value);
      });
      // 2.2查-获取Map的全部key
      Set set = hashOperations.keys("D:2023060804:01");
      set.forEach((key) -> {
          System.out.println("key=" + key);
      });
      // 2.3查-获取Map的全部value
      List list = hashOperations.values("D:2023060804:01");
      list.forEach((value) -> {
          System.out.println("value=" + value);
      });
      // 3.改
      hashOperations.put("D:2023060804:01", "hangzhou", "杭州-西湖");
      long time = 5000;
      log.info("{}秒后,删除D:2023060804:01队列", time / 1000);
      ThreadUtil.sleep(time);
      // 4.1删,(删除指定值)
      hashOperations.delete("D:2023060804:01", "hangzhou", "suzhou");
      // 4.2删,(删除全部)
      redisTemplate.delete("D:2023060804:01");
      // 5.设置超时
      hashOperations.put("D:2023060804:02", "hangzhou", "杭州");
      redisTemplate.boundValueOps("D:2023060804:02").expire(5, TimeUnit.MINUTES);
      redisTemplate.expire("D:2023060804:02", 10, TimeUnit.MINUTES);
      // 6.查询Hash的元素个数
      Long size = hashOperations.size("D:2023060804:02");
      System.out.println("查询Hash的元素个数,size=" + size);
      log.info("HashOperations操作Redis集群结束...");
      return "执行成功";
  }
  
}

3.3 Test verification

Use Postman test.

Request RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/operateCluster/f04

Above, thanks.

June 8, 2023

Guess you like

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