在Spring Boot微服务使用RedisTemplate操作Redis

记录:400

场景:在Spring Boot微服务使用RedisTemplate操作Redis缓存和队列。 使用ValueOperations操作Redis String字符串;使用ListOperations操作Redis List列表,使用HashOperations操作Redis Hash哈希散列,使用SetOperations操作Redis Set集合(无序集合),使用ZSetOperations操作Redis Zset(有序集合)。

版本:JDK 1.8,Spring Boot 2.6.3,redis-6.2.5

1.微服务中Redis配置信息

1.1在application.yml中Redis配置信息

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

1.2加载简要逻辑

Spring Boot微服务在启动时,自动注解机制会读取application.yml的注入到RedisProperties对象。在Spring环境中就能取到Redis相关配置信息了。

类全称:org.springframework.boot.autoconfigure.data.redis.RedisProperties

1.3在pom.xml添加依赖

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

2.配置RedisTemplate

2.1配置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 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解析

在配置RedisTemplate后,在Spring环境中,可以@Autowired自动注入方式注入操作Redis对象。比如:RedisTemplate、ValueOperations、ListOperations、HashOperations、SetOperations、ZSetOperations。

3.直接使用RedisTemplate操作

3.1简要说明

使用RedisTemplate的boundValueOps方法操作字符串,常用操作:增、查、改、删、设置超时等。

3.2操作示例

@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测试验证

使用Postman测试。

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

4.使用ValueOperations操作Redis String字符串

4.1简要说明

使用ValueOperations操作字符串,常用操作:增、查、改、删、设置超时等。

4.2操作示例

@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测试验证

使用Postman测试。

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

5.使用ListOperations操作Redis List列表

5.1简要说明

使用ListOperationsRedis List列表,常用操作:增、查、删、设置超时等。

5.2操作示例

@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测试验证

使用Postman测试。

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

6.使用HashOperations操作Redis Hash哈希散列

6.1简要说明

使用HashOperations操作Redis Hash哈希散列,常用操作:增、查、改、删、设置超时等。

6.2操作示例

@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测试验证

使用Postman测试。

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

7.使用SetOperations操作Redis Set集合(无序集合)

7.1简要说明

使用SetOperations操作Redis Set集合(无序集合),常用操作:增、查、删、设置超时等。

7.2操作示例

@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测试验证

使用Postman测试。

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

8.使用ZSetOperations操作Redis Zset(有序集合)

8.1简要说明

使用ZSetOperations操作Redis Zset(有序集合),常用操作:增、查、改、删、设置超时等。

8.2操作示例

@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测试验证

使用Postman测试。

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

9.可视化工具RedisDesktopManager

在可视化工具RedisDesktopManager中,可以查询Redis相关信息。

在ZSetOperations操作时,名称:CityInfo:Hangzhou06,以冒号分割,在RedisDesktopManager中会自动转换为文件夹方式展现。有多级冒号,就有多个文件夹。

TTL:591,是缓存超期时间,单位一般为秒。

 以上,感谢。

2023年4月12日

猜你喜欢

转载自blog.csdn.net/zhangbeizhen18/article/details/130119217