2023.1.13 关于在 Spring 中操作 Redis 服务器

目录

引言

前置工作

前置知识

实例演示

String 类型

List 类型

Set 类型

Hash 类型

ZSet 类型


引言

  • 进行下述操作的前提是 你的云服务器已经配置好了 ssh 端口转发
  • 即已经将云服务器的 Redis 端口映射到本地主机

注意:

  • 此处我们配置的端口号为 8888

可点击下方链接了解如何配置 ssh 端口转发 

Java 客户端连接 Redis 服务器

前置工作

1、在 SpringBoot 项目的 pom.xml 文件中添加依赖

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

2、编写 application.yml 配置文件

spring:
  redis:
    host: 127.0.0.1
    port: 8888

前置知识

  • 相较于使用 Jedis 库通过 Jedis 对象里的各种方法来操作 Redis 
  • 此处 Spring 则是通过 StringRedistemplate 来操作 Redis 

注意:

  • StringRedistemplate 类提供的方法相较于 Jedis 对象里的各种方法,具有较大差异

  • StringRedistemplate 类将操作 Redis 的方法分成了几个类别,分门别类的来进行组织
  • 即做了进一步的封装!
  • 所以此处提供的一些接口风格和原生 Redis 命令就有一定的差异了
  • 首先其初心是希望通过上述重新的封装,让接口用起来更简单
  • 在我看来其初心并未达成,反而因为和 Redis 原生命令的差异,提高了使用者学习成本

补充:

  • Spring 最原始提供的类是 RedisTemplate
  • StringRedistemplate 类是 RedisTemplate 的子类 专门用来处理 文本数据的

  • 但是 Redistemplate 类留了一个后手,让我们随时能够执行到 Redis 原生的命令
  • 即通过 execute 方法

实例理解

  • 此处我们想要在 Redis 中执行 FLUSHALL 命令
stringRedisTemplate.execute((RedisConnection connection) -> {
//    execute 要求回调方法中必须写 return 语句,返回个东西
//    这个回调返回的对象,就会作为 execute 本身的返回值
    connection.flushAll();
    return null;
});

  • 函数式接口,相当于一个回调函数
  • 就在回调里,写咱们要执行的 redis 命令
  • 这个回调就会被 RedisTemplate 内部进行执行

补充:

  • 当我们点击查看 RedisCallback<T> 的源码

  • 此处的 RedisConnection 就代表了 Redis 链接,对标 Jedis 对象

实例演示

  • 此处 Redis 测试的各种方法,均通过 Controller 提供的 HTTP 接口来触发的
  • 即我们可先创建一个 MyController 类,并在该类中进行测试代码的编写
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;


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

//   ...
}

String 类型

    @GetMapping("/testString")
    @ResponseBody
    public String testString() {
//        先清除之前的数据
        stringRedisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
            return null;
        });

        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";
}

运行结果:


List 类型

    @GetMapping("/testList")
    @ResponseBody
    public String testList() {
//        先清除之前的数据
        stringRedisTemplate.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";
    }

运行结果:


Set 类型

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

运行结果:


Hash 类型

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

运行结果:


ZSet 类型

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

        stringRedisTemplate.opsForZSet().add("key","xxl",10);
        stringRedisTemplate.opsForZSet().add("key","wml",20);
        stringRedisTemplate.opsForZSet().add("key","shw",30);

        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","xxl");
        System.out.println("score = " + score);

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

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

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

        return "OK";
    }

运行结果:

  • 17
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茂大师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值