Redis的Spring客户端使用小结

 更新时间:2025年04月07日 09:24:52   作者:19岁微操大师  
在Spring中使用Redis,可以极大地提升应用程序的性能和响应速度,本文主要介绍了Redis的Spring客户端使用小结,具有一定的参考价值,感兴趣的可以了解一下

前面使用 Jedis 时, 是借助 Jedis 对象中的各种方法来对 Redis 进行操作. 而在 Spring 框架中, 则是通过 StringRedisTemplate 来操作 Redis. 最开始提供的类是 RedisTemplate, StringRedisTemplate 是 RedisTemplate 的子类, 专门用于处理文本数据.

0. 配置 Spring 的 Redis环境

(1) 引入 Redis 的 Spring 依赖

选中 NoSQL 中的 Spring Data Redis (Access+Driver) 依赖.

image-20250305173733774

(2) 写 Spring 配置文件

application.yml:

spring:
  data:
    redis:
      host: 127.0.0.1
      port: 8888

(3) 创建 Controller 类, 并注入 StringRedisTemplate 对象.

@RestController
public class MyController { 
    @Autowired
    StringRedisTemplate stringRedisTemplate;
}

[!NOTE]

这里的 RedisTemplate 将 Redis 中的命令, 又做了进一步封装, 分成了几个类别 (每个类别操作特定的数据类型)

  • opsForValue(): 专门操作 string 类型.
  • opsForList(): 专门操作 list 类型.
  • opsForSet(): 专门操作 set 类型.
  • opsForHash(): 专门操作 hash 类型.
  • opsForZSet(): 专门操作 zset 类型.

这样一来, 它提供的一些接口风格和原生的Redis命令就存在一定差异.

还有一点要注意的是: Spring 并没有封装 Redis 的所有命令 (如 flushAll 就没有封装), 此时我们可以使用 execute 方法来使用 Redis 的原始命令.

例如:

stringRedisTemplate.execute((RedisConnection connection) -> {
            // execute 要求回调方法中必须写 return 语句,返回个东西
            // 这个回调返回的对象,就会作为 execute 本身的返回值
            connection.flushAll();
            return null;
        });
//这里的RedisConnection对象, 就相当于Jedis里的Jedis对象.

1.使用 string

@RestController
public class MyController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/testString")
    public String testString() {
        stringRedisTemplate.opsForValue().set("key", "111");
        stringRedisTemplate.opsForValue().set("key2", "222");
        stringRedisTemplate.opsForValue().set("key3", "333");

        String value = stringRedisTemplate.opsForValue().get("key");
        System.out.println("value: " + value);

        return "OK";
    }
}
  • 请求结果:

postman:

image-20250305182121278

日志:

image-20250305182205671

2. 使用 list

    @GetMapping("/testList")
    public String testList() {
        // 先清除之前的数据
        tringRedisTemplate.execute((RedisConnection connection) -> {
            // execute 要求回调方法中必须写 return 语句,返回个东西
            // 这个回调返回的对象,就会作为 execute 本身的返回值
            connection.flushAll();
            return null;
        });

        stringRedisTemplate.opsForList().leftPush("key", "111");
        stringRedisTemplate.opsForList().leftPush("key", "222");
        stringRedisTemplate.opsForList().leftPush("key", "333");

        String value = stringRedisTemplate.opsForList().rightPop("key");
        System.out.println("value: " + value);
        value = stringRedisTemplate.opsForList().rightPop("key");
        System.out.println("value: " + value);
        value = stringRedisTemplate.opsForList().rightPop("key");
        System.out.println("value: " + value);

        return "OK";
    }

运行结果:

image-20250305195044857

3. 使用 set

    @GetMapping("/testSet")
    public String testSet() {
        stringRedisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
            return null;
        });

        stringRedisTemplate.opsForSet().add("key", "111", "222", "333");
        Set<String> result = stringRedisTemplate.opsForSet().members("key");
        System.out.println("result: " + result);

        Boolean exists = stringRedisTemplate.opsForSet().isMember("key", "111");
        System.out.println("exists: " + exists);

        Long count = stringRedisTemplate.opsForSet().size("key");
        System.out.println("count: " + count);

        stringRedisTemplate.opsForSet().remove("key", "111", "222");
        result = stringRedisTemplate.opsForSet().members("key");
        System.out.println("result: " + result);

        return "OK";
    }

运行结果:

image-20250305195721095

4. 使用 Hash

    @GetMapping("/testHash")
    public String testHash() {
        stringRedisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
            return null;
        });

        stringRedisTemplate.opsForHash().put("key", "f1", "111");
        stringRedisTemplate.opsForHash().put("key", "f2", "222");
        stringRedisTemplate.opsForHash().put("key", "f3", "333");

        String value = (String) stringRedisTemplate.opsForHash().get("key", "f1");
        System.out.println("value: " + value);

        Boolean exists = stringRedisTemplate.opsForHash().hasKey("key", "f1");
        System.out.println("exists: " + exists);

        stringRedisTemplate.opsForHash().delete("key", "f1", "f2");

        Long size = stringRedisTemplate.opsForHash().size("key");
        System.out.println("size: " + size);

        return "OK";
    }

运行结果:

image-20250305201837017

5. 使用 zset

    @GetMapping("/testZSet")
    public String testZSet() {
        stringRedisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
            return null;
        });

        stringRedisTemplate.opsForZSet().add("key", "zhangsan", 10D);
        stringRedisTemplate.opsForZSet().add("key", "lisi", 20D);
        stringRedisTemplate.opsForZSet().add("key", "wangwu", 30D);

        Set<String> members = stringRedisTemplate.opsForZSet().range("key", 0, -1);
        System.out.println("members: " + members);

        Set<ZSetOperations.TypedTuple<String>> membersWithScore = stringRedisTemplate.opsForZSet().rangeWithScores("key", 0, -1);
        System.out.println("membersWithScore: " + membersWithScore);

        Double score = stringRedisTemplate.opsForZSet().score("key", "zhangsan");
        System.out.println("score: " + score);

        stringRedisTemplate.opsForZSet().remove("key", "zhangsan");

        Long size = stringRedisTemplate.opsForZSet().size("key");
        System.out.println("size: " + size);

        Long rank = stringRedisTemplate.opsForZSet().rank("key", "lisi");
        System.out.println("rank: " + rank);

        return "OK";
    }

运行结果:

image-20250305202913409

到此这篇关于Redis的Spring客户端使用小结的文章就介绍到这了,更多相关Redis Spring客户端使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 解析Redis的缓存类型

    解析Redis的缓存类型

    本文主要介绍了Redis的缓存类型,主要介绍了4种缓存,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • Redis fork进程分配不到内存解决方案

    Redis fork进程分配不到内存解决方案

    这篇文章主要介绍了Redis fork进程分配不到内存解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Redis中的数据过期策略详解

    Redis中的数据过期策略详解

    这篇文章主要介绍了Redis中的数据过期策略,文中通过示例代码介绍的很详细,相信对大家的理解和学习具有一定的参考借鉴价值,有需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-01-01
  • Redis整合SpringBoot的RedisTemplate实现类(实例详解)

    Redis整合SpringBoot的RedisTemplate实现类(实例详解)

    这篇文章主要介绍了Redis整合SpringBoot的RedisTemplate实现类,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • redis中的事务操作案例分析

    redis中的事务操作案例分析

    这篇文章主要介绍了redis中的事务操作案例,结合具体实例形式详细分析了redis事务操作的概念、原理、使用技巧与相关注意事项,需要的朋友可以参考下
    2019-07-07
  • redis4.0入门小结

    redis4.0入门小结

    这篇文章主要介绍了redis4.0入门小结,文中通过示例和概念介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • 基于Redis实现分布式锁以及任务队列

    基于Redis实现分布式锁以及任务队列

    这篇文章主要介绍了基于Redis实现分布式锁以及任务队列,需要的朋友可以参考下
    2015-11-11
  • 浅谈Redis阻塞的9种情况

    浅谈Redis阻塞的9种情况

    本文主要介绍了浅谈Redis阻塞的9种情况,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • redis生成全局id的实现步骤

    redis生成全局id的实现步骤

    生成全局唯一的标识符是非常常见的需求,本文主要介绍了redis生成全局id的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-05-05
  • 详解redis集群的三种方式

    详解redis集群的三种方式

    Redis三种集群方式分别是主从复制,哨兵模式,Cluster集群,这篇文章主要介绍了redis集群的三种方式,本文给大家介绍的非常详细,需要的朋友可以参考下
    2022-07-07

最新评论