ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

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

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.1port: 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 {@Autowiredprivate StringRedisTemplate stringRedisTemplate;//   ...
}

String 类型

    @GetMapping("/testString")@ResponseBodypublic 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")@ResponseBodypublic 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")@ResponseBodypublic 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")@ResponseBodypublic 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")@ResponseBodypublic 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";}

运行结果:

返回列表