欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在Spring里如何玩转Redis操作

最编程 2024-02-19 22:31:57
...

目录

创建项目

​编辑 配置Redis

创建类

StringRedisTemplate

 set / get

list

set 

Hash 

zset


新年快乐!!!!

创建项目

        选中maven项目,然后选择java8,输入名称之后,点击next。

        随后选择依赖:

 配置Redis

        找到配置文件 application.properties:

当然你也可以将其改为yml:

这里我们使用yml文件:

添加配置:

spring:
  redis:
    host: 127.0.0.1
    port: 8888

这里通过ssh转发,来实现连接服务器上的Redis服务器。

创建类

        创建一个MyController类

 

        spring中使用StringRedisTemplate来操作Redis,其实最原始的提供的类是RedisTemplate,但是太麻烦了,现在的StringRedisTemplate是RedisTemplate的子类,专门用来处理 文本数据的。

        MyController内容如下:

package com.example.redisbyspring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RestController;

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

}

         后续将在这个类中进行Redis的操作。

StringRedisTemplate

        通过在一个请求方法中进行对象.的操作,发现好像和我们预想的不一样:

        通过这个类的实例对象,并没有发现很直观的有get和set方法,但是似乎他们的前面都加上了posFor。这是为什么?

        其实,此处的Template就是把这些操作Redis的方法,分成了几个类别,例如,操作list的是一个类,他就是opsForList(),以此类推做了进一步封装:

        后续的stringRedisTemplate是StringRedisTemplate的子类。 

        在进行jedis集成spring的测试代码中,需要清除干扰项目,也就是里面可能已经存在一些key,对我们后面的测试造成影响,需要使用flashAll来清除所有的key。

         但是我们翻阅了stringRedisTemplate的方法,发现没有flashall操作:

        RedisTemplate留了一个后手,让我们随时可以执行到Redis的原生命令。Redis集成spring中有一个 execute方法,用来执行Redis的原生命令。

        里面有一个RedisCallBack是一个回调函数:

public interface RedisCallback<T> {
    @Nullable
    T doInRedis(RedisConnection connection) throws DataAccessException;
}

         输入相关参数就可以进行执行Redis原生命令了:

        redisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
        });

         但是有个问题,就是这段代码的execute会报错:

        这是什么回事?这是因为当前的execute方法会有一个返回结果,但是当前不需要返回什么,就返回一个null即可:

        redisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
            return null;
        });

 

 set / get

        使用StringRedisTemplate的实例中的方法来 进行set和get方法操作Redis。

package com.example.redisbyspring;

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

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

    @GetMapping("/testString")
    @ResponseBody
    public String testString() {
        redisTemplate.opsForValue().set("key1","value1");
        redisTemplate.opsForValue().set("key2","value2");
        redisTemplate.opsForValue().set("key3","value3");

        String ret1 = redisTemplate.opsForValue().get("key1");
        System.out.println(ret1);

        String ret2 = redisTemplate.opsForValue().get("key2");
        System.out.println(ret2);

        String ret3 = redisTemplate.opsForValue().get("key3");
        System.out.println(ret3);
        return "ok";
    }

}

        浏览器访问接口:

        返回:

        控制台输出:

 

list

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

        // list的lpush
        redisTemplate.opsForList().rightPush("key","111");

        // list一次性添加多个元素
        redisTemplate.opsForList().rightPushAll("key","222","333","444");
        // 此时的列表内容为[111,222,333,444]
        // pop
        redisTemplate.opsForList().leftPop("key");
        redisTemplate.opsForList().rightPop("key");
        // 此时list表的内容为[222,333]
        // list的lrange
        List<String> list = redisTemplate.opsForList().range("key",0, -1);
        System.out.println(list);
        return "listOk";
    }

 访问对应的链接,输出:

set 

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

        // set的sadd
        redisTemplate.opsForSet().add("key","111","222","333");

        // set的smembers
        Set<String> set = redisTemplate.opsForSet().members("key");
        System.out.println(set);

        // set的sismember
        Boolean bool = redisTemplate.opsForSet().isMember("key","111");
        System.out.println(bool);

        // set中的scard
        Long count = redisTemplate.opsForSet().size("key");
        System.out.println(count);

        // set中srem
        count = redisTemplate.opsForSet().remove("key","111");
        System.out.println("删除的个数:" + count);
        set = redisTemplate.opsForSet().members("key");
        System.out.println(set);

        return "setOk";
    }

         访问此链接,输出:

Hash 

    @GetMapping("/testHash")
    @ResponseBody
    public String testHash() {
        redisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll(); // 刷新Redis数据
            return null;
        });

        // hash中的hset
        redisTemplate.opsForHash().put("key","f1","v1");

        // hmset
        Map<String,String> map = new HashMap<>();
        map.put("f2","v2");
        map.put("f3","v3");
        redisTemplate.opsForHash().putAll("key",map);

        // hget
        String ret = (String) redisTemplate.opsForHash().get("key","f1");
        System.out.println(ret);

        // hexists
        Boolean exists = redisTemplate.opsForHash().hasKey("key","f1");
        System.out.println(exists);

        // hdel
        Long numsOfDel = redisTemplate.opsForHash().delete("key","f1");
        System.out.println(numsOfDel);

        // hlen
        Long len = redisTemplate.opsForHash().size("key");
        System.out.println(len);

        // hkeys
        Set<Object> set = redisTemplate.opsForHash().keys("key");
        System.out.println(set);

        // hval
        List<Object> list =  redisTemplate.opsForHash().values("key");
        System.out.println(list);

        Map<Object,Object> map1 = redisTemplate.opsForHash().entries("key");
        System.out.println(map1);
        return "hashOK";

    }

 输出:

zset

 

    @GetMapping("/testZset")
    @ResponseBody
    public String testZset() {
        redisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll(); // 刷新Redis数据
            return null;
        });

        // zadd
        redisTemplate.opsForZSet().add("key","zhangsan",10.2);
        redisTemplate.opsForZSet().add("key","lisi",11.3);
        redisTemplate.opsForZSet().add("key","wangwu",12.4);

        // zrange
        Set<String> set = redisTemplate.opsForZSet().range("key",0, -1);
        System.out.println(set);

        // zrangewithScores
        Set<ZSetOperations.TypedTuple<String>> setWithScores = redisTemplate.opsForZSet().rangeWithScores("key",0,-1);
        System.out.println(setWithScores);

        // zscore
        Double scoreOfLisi = redisTemplate.opsForZSet().score("key","lisi");
        System.out.println(scoreOfLisi);

        // zrem
        redisTemplate.opsForZSet().remove("key","lisi");
        setWithScores = redisTemplate.opsForZSet().rangeWithScores("key",0,-1);
        System.out.println(setWithScores);

        // zrank
        Long rank = redisTemplate.opsForZSet().rank("key","lisi");
        System.out.println(rank);
        rank = redisTemplate.opsForZSet().rank("key","wangwu");
        System.out.println(rank);
        return "zsetOK";
    }

输出:

更多详细内容可以查阅spring官方文档:
Spring BootLevel up your Java code and explore what Spring can do for you.https://spring.io/projects/spring-boot

推荐阅读