在spring中操作Redis

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 在spring中操作Redis


创建项目

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

输出:


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
3天前
|
存储 NoSQL Java
在Spring Boot中使用Redis生成订单号,并且保证当天有效性
在Spring Boot中使用Redis生成订单号,并且保证当天有效性
21 4
|
3天前
|
缓存 NoSQL Java
在 Spring Boot 应用中使用 Spring Cache 和 Redis 实现数据查询的缓存功能
在 Spring Boot 应用中使用 Spring Cache 和 Redis 实现数据查询的缓存功能
12 0
|
3天前
|
NoSQL Java Redis
如何在 Java 中操作这些 Redis 数据结构的基本方法
如何在 Java 中操作这些 Redis 数据结构的基本方法
9 2
|
3天前
|
监控 NoSQL Java
在 Spring Boot 中实现 Redis 的发布/订阅功能可以通过 RedisTemplate 和消息监听器来完成
在 Spring Boot 中实现 Redis 的发布/订阅功能可以通过 RedisTemplate 和消息监听器来完成
9 1
|
2天前
|
NoSQL Java API
Spring Boot与Redis的整合
Spring Boot与Redis的整合
|
2天前
|
NoSQL Java Redis
Redis中的键值过期操作
Redis中的键值过期操作
|
3天前
|
NoSQL Java Redis
Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis
Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis
|
存储 NoSQL 数据库
redis 超全的操作
来源:http://www.cnblogs.com/NONE/archive/2011/05/30/2062904.html Redis::__construct 描述: 创建一个Redis客户端 范例: $redis = new Redis(); connect, open 描述: 实例连接到一个Redis. 参数:h
1560 0
|
1月前
|
NoSQL Linux Redis
Redis -- 安装客户端redis-plus-plus
Redis -- 安装客户端redis-plus-plus
55 0
|
5天前
|
NoSQL Redis Windows
win10下Redis安装、启动教程
win10下Redis安装、启动教程
14 2