Use RedisTemplate para operar Redis en microservicios Spring Boot

Registros : 400

Escenario : use RedisTemplate para operar la memoria caché y la cola de Redis en los microservicios de Spring Boot. Use ValueOperations para operar Redis String; use ListOperations para operar Redis List, use HashOperations para operar Redis Hash, use SetOperations para operar la colección Redis Set (colección no ordenada), use ZSetOperations para operar Redis Zset (colección ordenada).

Versiones : JDK 1.8, Spring Boot 2.6.3, redis-6.2.5

1. Información de configuración de Redis en microservicios

1.1 Información de configuración de Redis en application.yml

spring:
  redis:
    host: 192.168.19.203
    port: 28001
    password: 12345678
    timeout: 50000

1.2 Lógica breve de carga

Cuando se inicia el microservicio Spring Boot, el mecanismo de anotación automática leerá application.yml y lo inyectará en el objeto RedisProperties. La información de configuración relacionada con Redis se puede obtener en el entorno Spring.

Nombre completo de la clase: org.springframework.boot.autoconfigure.data.redis.RedisProperties

1.3 Agregar dependencias en pom.xml

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

2. Configurar Plantilla Redis

2.1 Configurar Plantilla Redis

@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 ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForValue();
  }
  @Bean
  public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForList();
  }
  @Bean
  public HashOperations<String, Object, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForHash();
  }
  @Bean
  public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForSet();
  }
  @Bean
  public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForZSet();
  }
}

2.2 Análisis

Después de configurar RedisTemplate, en el entorno Spring, el método de inyección automática @Autowired se puede usar para inyectar y operar el objeto Redis. Por ejemplo: RedisTemplate, ValueOperations, ListOperations, HashOperations, SetOperations, ZSetOperations.

3. Usar directamente la operación RedisTemplate

3.1 Breve descripción

Use el métodoboundValueOps de RedisTemplate para operar cadenas, operaciones comunes: agregar, verificar, modificar, eliminar, establecer el tiempo de espera, etc.

3.2 Ejemplo de operación

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
  @Autowired
  private RedisTemplate redisTemplate;
  /**
   * 操作缓存方式,直接使用RedisTemplate
   * 对应写命令: SET key value
   * 对应读命令: GET key
   */
  @GetMapping("/redisTemplate")
  public Object loadData01() {
    log.info("RedisTemplate操作开始...");
    // 1.增
    redisTemplate.boundValueOps("CityInfo:Hangzhou01").set("杭州");
    // 2.查
    Object result01 = redisTemplate.boundValueOps("CityInfo:Hangzhou01").get();
    log.info("result01 = " + result01.toString());
    // 3.改
    redisTemplate.boundValueOps("CityInfo:Hangzhou01").set("杭州-西湖");
    // 4.删
    redisTemplate.delete("CityInfo:Hangzhou01");
    // 5.1设置超时(方式一)
    redisTemplate.boundValueOps("CityInfo:Hangzhou01").set("杭州-西湖");
    redisTemplate.expire("CityInfo:Hangzhou01", 5, TimeUnit.MINUTES);
    // 5.2设置超时(方式二)
    redisTemplate.boundValueOps("CityInfo:Hangzhou01-01").set("杭州", 5, TimeUnit.MINUTES);
    log.info("RedisTemplate操作结束...");
    return "执行成功";
  }
}

3.3 Verificación de prueba

Utilice la prueba del cartero.

Solicitud RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/redisTemplate

4. Use ValueOperations para operar Redis String

4.1 Breve descripción

Use ValueOperations para manipular cadenas, operaciones comunes: agregar, verificar, modificar, eliminar, establecer tiempo de espera, etc.

4.2 Ejemplo de operación

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private ValueOperations valueOperations;
  /**
   * 操作String,使用ValueOperations
   * 对应写命令: SET key value
   * 对应读命令: GET key
   */
  @GetMapping("/valueOperations")
  public Object loadData02() {
    log.info("ValueOperations操作开始...");
    // 1.增
    valueOperations.set("CityInfo:Hangzhou02", "杭州");
    valueOperations.set("CityInfo:Hangzhou02", "苏州");
    // 2.查
    Object result01 = valueOperations.get("CityInfo:Hangzhou02");
    log.info("result01 = " + result01.toString());
    // 3.改
    valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");
    // 4.删
    String result02 = (String) valueOperations.getAndDelete("CityInfo:Hangzhou02");
    redisTemplate.delete("CityInfo:Hangzhou02");
    // 5.1设置超时(方式一)
    valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");
    valueOperations.getAndExpire("CityInfo:Hangzhou02", 5, TimeUnit.MINUTES);
    // 5.2设置超时(方式二)
    valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");
    redisTemplate.expire("CityInfo:Hangzhou02", 10, TimeUnit.MINUTES);
    // 6.查询Value的字节大小
    Long size =valueOperations.size("CityInfo:Hangzhou02");
    System.out.println("缓存字节大小,size="+size +" bytes");
    log.info("ValueOperations操作结束...");
    return "执行成功";
  }
}

4.3 Verificación de prueba

Utilice la prueba del cartero.

Solicitud RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/valueOperations

5. Use ListOperations para operar la lista Redis List

5.1 Breve descripción

Use la lista ListOperationsRedis List, operaciones comunes: agregar, verificar, eliminar, establecer el tiempo de espera, etc.

5.2 Ejemplo de operación

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private ListOperations listOperations;
  /**
   * 操作List,使用ListOperations
   * 对应写命令: LPUSH 队列名称 值
   * 对应读命令: LPOP 队列名称
   * 对应写命令: RPUSH 队列名称 值
   * 对应读命令: RPOP 队列名称
   */
  @GetMapping("/listOperations")
  public Object loadData03() {
    log.info("ListOperations操作开始...");
    // 1.增
    listOperations.leftPush("CityInfo:Hangzhou03", "杭州");
    listOperations.rightPush("CityInfo:Hangzhou03", "苏州");
    // 2.查,查出队列指定范围元素,不会删除队列里面数据,(0,-1)查出全部元素
    listOperations.leftPush("CityInfo:Hangzhou03", "杭州");
    listOperations.leftPush("CityInfo:Hangzhou03", "苏州");
    List cityList = redisTemplate.boundListOps("CityInfo:Hangzhou03").range(0, -1);
    cityList.forEach((value)->{
        System.out.println("value="+value);
    });
    // 3.取,逐个取出队列元素(取出一个元素后,队列就没有这个元素了)
    Object city01 = listOperations.leftPop("CityInfo:Hangzhou03");
    Object city02 = listOperations.rightPop("CityInfo:Hangzhou03");
    log.info("city01=" + city01 + ",city02=" + city02);
    // 4.删
    listOperations.leftPush("CityInfo:Hangzhou03", "杭州");
    listOperations.leftPush("CityInfo:Hangzhou03", "苏州");
    redisTemplate.delete("CityInfo:Hangzhou03");
    // 5.设置超时
    listOperations.leftPush("CityInfo:Hangzhou03", "上海");
    redisTemplate.boundValueOps("CityInfo:Hangzhou03").expire(5, TimeUnit.MINUTES);
    redisTemplate.expire("CityInfo:Hangzhou03", 10, TimeUnit.MINUTES);
    // 6.查询List的元素个数
    Long size =listOperations.size("CityInfo:Hangzhou03");
    System.out.println("查询List的元素个数,size="+size);
    log.info("ListOperations操作结束...");
    return "执行成功";
  }
}

5.3 Verificación de prueba

Utilice la prueba del cartero.

Solicitud RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/listOperations

6. Use HashOperations para operar el hash Redis Hash

6.1 Breve descripción

Use HashOperations para operar hashes Redis Hash, operaciones comunes: agregar, verificar, modificar, eliminar, establecer el tiempo de espera, etc.

6.2 Ejemplo de operación

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private HashOperations hashOperations;
  /**
   * 操作Hash,使用HashOperations
   * 对应写命令: HMSET
   * 对应读命令: HGETALL
   * 本质就是在一个key对应存储了一个Map
   */
  @GetMapping("/hashOperations")
  public Object loadData04() {
    log.info("HashOperations操作开始...");
    // 1.增
    hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州");
    hashOperations.put("CityInfo:Hangzhou04", "suzhou", "苏州");
    // 2.1查-获取map键值对数据
    Map resultMap = hashOperations.entries("CityInfo:Hangzhou04");
    resultMap.forEach((key, value) -> {
        System.out.println("key=" + key + ",value=" + value);
    });
    // 2.2查-获取Map的全部key
    Set set = hashOperations.keys("CityInfo:Hangzhou04");
    set.forEach((key) -> {
        System.out.println("key=" + key);
    });
    // 2.3查-获取Map的全部value
    List list = hashOperations.values("CityInfo:Hangzhou04");
    list.forEach((value) -> {
        System.out.println("value=" + value);
    });
    // 3.改
    hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州-西湖");
    // 4.1删,(删除指定值)
    hashOperations.delete("CityInfo:Hangzhou04", "hangzhou", "suzhou");
    // 4.2删,(删除全部)
    redisTemplate.delete("CityInfo:Hangzhou04");
    // 5.设置超时
    hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州");
    redisTemplate.boundValueOps("CityInfo:Hangzhou04").expire(5, TimeUnit.MINUTES);
    redisTemplate.expire("CityInfo:Hangzhou04", 10, TimeUnit.MINUTES);
    // 6.查询Hash的元素个数
    Long size =hashOperations.size("CityInfo:Hangzhou04");
    System.out.println("查询Hash的元素个数,size="+size);
    log.info("HashOperations操作结束...");
    return "执行成功";
  }
}

6.3 Verificación de prueba

Utilice la prueba del cartero.

Solicitud RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/hashOperations

7. Use SetOperations para operar la colección Redis Set (colección desordenada)

7.1 Breve descripción

Use SetOperations para operar la colección Redis Set (colección no ordenada), operaciones comunes: agregar, verificar, eliminar, establecer tiempo de espera, etc.

7.2 Ejemplo de operación

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private SetOperations setOperations;
  /**
   * 操作ZSet,使用ZSetOperations,有序排列且无重复数据
   * 对应写命令: ZADD
   * 对应读命令: SPOP
   */
  @GetMapping("/zSetOperations")
  public Object loadData06() {
    log.info("ZSetOperations操作开始...");
    // 1.增
    zSetOperations.add("CityInfo:Hangzhou06", "杭州", 20);
    zSetOperations.add("CityInfo:Hangzhou06", "苏州", 10);
    zSetOperations.add("CityInfo:Hangzhou06", "上海", 30);
    zSetOperations.add("CityInfo:Hangzhou06", "北京", 101);
    zSetOperations.add("CityInfo:Hangzhou06", "宁波", 999);
    // 2.1查(通过下标查值,从0开始取第一个值)
    Set set = zSetOperations.range("CityInfo:Hangzhou06", 1, 4);
    set.forEach((value) -> {
        System.out.println("value=" + value);
    });
    // 2.2查(通过Score查值)
    set = zSetOperations.rangeByScore("CityInfo:Hangzhou06", 29, 60);
    set.forEach((value) -> {
        System.out.println("value=" + value);
    });
    // 3.改
    zSetOperations.add("CityInfo:Hangzhou06", "杭州", 99);
    // 4.1取(取出Score最大的值,取出后队列中值会删除)
    ZSetOperations.TypedTuple obj1 = zSetOperations.popMax("CityInfo:Hangzhou06");
    System.out.println("取出最大值,value=" + obj1.getValue() + ",Score=" + obj1.getScore());
    // 4.2取(取出Score最小的值,取出后队列中值会删除)
    ZSetOperations.TypedTuple obj2 = zSetOperations.popMin("CityInfo:Hangzhou06");
    System.out.println("取出最小值,value=" + obj2.getValue() + ",Score=" + obj2.getScore());
    // 5.1删除指定值
    zSetOperations.remove("CityInfo:Hangzhou06", "上海");
    // 5.2按照Score分数大小删除
    zSetOperations.removeRangeByScore("CityInfo:Hangzhou06", 1, 100);
    // 5.3删(删除全部)
    redisTemplate.delete("CityInfo:Hangzhou06");
    // 6.设置超时
    zSetOperations.add("CityInfo:Hangzhou06", "杭州", 21);
    zSetOperations.add("CityInfo:Hangzhou06", "苏州", 11);
    redisTemplate.boundValueOps("CityInfo:Hangzhou06").expire(5, TimeUnit.MINUTES);
    redisTemplate.expire("CityInfo:Hangzhou06", 10, TimeUnit.MINUTES);
    // 7.查询ZSet的元素个数
    Long size =zSetOperations.size("CityInfo:Hangzhou06");
    System.out.println("查询ZSet的元素个数,size="+size);
    log.info("ZSetOperations操作结束...");
    return "执行成功";
  }
}

7.3 Verificación de prueba

Utilice la prueba del cartero.

Solicitud RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/setOperations

8. Use ZSetOperations para operar Redis Zset (colección ordenada)

8.1 Breve descripción

Use ZSetOperations para operar Redis Zset (colección ordenada), operaciones comunes: agregar, verificar, modificar, eliminar, establecer tiempo de espera, etc.

8.2 Ejemplo de operación

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private ZSetOperations zSetOperations;
  /**
   * 操作ZSet,使用ZSetOperations,有序排列且无重复数据
   * 对应写命令: ZADD
   */
  @GetMapping("/zSetOperations")
  public Object loadData06() {
    log.info("ZSetOperations操作开始...");
    // 1.增
    zSetOperations.add("CityInfo:Hangzhou06", "杭州", 20);
    zSetOperations.add("CityInfo:Hangzhou06", "苏州", 10);
    zSetOperations.add("CityInfo:Hangzhou06", "上海", 30);
    zSetOperations.add("CityInfo:Hangzhou06", "北京", 101);
    zSetOperations.add("CityInfo:Hangzhou06", "宁波", 999);
    // 2.1查(通过下标查值,从0开始取第一个值)
    Set set = zSetOperations.range("CityInfo:Hangzhou06", 1, 4);
    set.forEach((value) -> {
        System.out.println("value=" + value);
    });
    // 2.2查(通过Score查值)
    set = zSetOperations.rangeByScore("CityInfo:Hangzhou06", 29, 60);
    set.forEach((value) -> {
        System.out.println("value=" + value);
    });
    // 3.改
    zSetOperations.add("CityInfo:Hangzhou06", "杭州", 99);
    // 4.1取(取出Score最大的值,取出后队列中值会删除)
    ZSetOperations.TypedTuple obj1 = zSetOperations.popMax("CityInfo:Hangzhou06");
    System.out.println("取出最大值,value=" + obj1.getValue() + ",Score=" + obj1.getScore());
    // 4.2取(取出Score最小的值,取出后队列中值会删除)
    ZSetOperations.TypedTuple obj2 = zSetOperations.popMin("CityInfo:Hangzhou06");
    System.out.println("取出最小值,value=" + obj2.getValue() + ",Score=" + obj2.getScore());
    // 5.1删除指定值
    zSetOperations.remove("CityInfo:Hangzhou06", "上海");
    // 5.2按照Score分数大小删除
    zSetOperations.removeRangeByScore("CityInfo:Hangzhou06", 1, 100);
    // 5.3删(删除全部)
    redisTemplate.delete("CityInfo:Hangzhou06");
    // 6.设置超时
    zSetOperations.add("CityInfo:Hangzhou06", "杭州", 21);
    zSetOperations.add("CityInfo:Hangzhou06", "苏州", 11);
    redisTemplate.boundValueOps("CityInfo:Hangzhou06").expire(5, TimeUnit.MINUTES);
    redisTemplate.expire("CityInfo:Hangzhou06", 10, TimeUnit.MINUTES);
    // 7.查询ZSet的元素个数
    Long size =zSetOperations.size("CityInfo:Hangzhou06");
    System.out.println("查询ZSet的元素个数,size="+size);
    log.info("ZSetOperations操作结束...");
    return "执行成功";
  }
}

8.3 Verificación de prueba

Utilice la prueba del cartero.

Solicitud RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/zSetOperations

9. Herramienta de visualización RedisDesktopManager

En la herramienta de visualización RedisDesktopManager, puede consultar información relacionada con Redis.

Al operar ZSetOperations, el nombre: CityInfo:Hangzhou06, separado por dos puntos, se convertirá automáticamente en una carpeta en RedisDesktopManager. Con varios niveles de dos puntos, hay varias carpetas.

TTL: 591, que es el tiempo de caducidad de la memoria caché, generalmente en segundos.

 Arriba, gracias.

12 de abril de 2023

Supongo que te gusta

Origin blog.csdn.net/zhangbeizhen18/article/details/130119217
Recomendado
Clasificación