在Spring中使用Redis

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Redis 版,经济版 1GB 1个月
简介: 在Spring中使用Redis

端口怎么设置,看我前一篇文章

前面使用jedis,通过Jedis对象中各种方法来操作redis的。

此处Spring中则是通过StringRedisTemplate来操作redis。

最原始提供的类是RedisTemplate

StringRedisTemplate是RedisTemplate的子类,专门处理文本数据的

这个类提供的方法,相比较于Jedis还是有区别的。

做了进一步封装,得到了专门操作字符串的对象,得到了专门操作xx的对象。初心是为了接口更简单。

字符串常用操作

set-get    设置,获取

有些操作封装来,有些没有封装,比如删库,比如ping

RedisTemplate留了一手,让我们随意执行redis的原操作

execute方法,RedisCallback函数式接口,相当于一个回调函数,就在回调里,写我们要执行的redis命令,这个回调就会被RedisTemplate内部进行执行了。

链表常用操作

leftpop和rightpop,头删,尾删

Set常用操作

Hash常用操作

Zset常用操作

package com.example.demo.Controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.util.Set;
 
//后续redis测试的各种功能,都通过这个Controller提供的http接口
@Controller
public class MYController {
    @Autowired
    private StringRedisTemplate redisTemplate;
 
    @GetMapping("/testString")
    @ResponseBody
    public String testString() {
        redisTemplate.opsForValue().set("key", "111");
        redisTemplate.opsForValue().set("key", "222");
        redisTemplate.opsForValue().set("key", "333");
        String value = redisTemplate.opsForValue().get("key");
        System.out.println("value:" + value);
        return "ok";
    }
 
    @GetMapping("/testList")
    @ResponseBody
    public String testList() {
        //先删库
        redisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
            //execute要求回调方法中必须写return,返回个东西
            //这个回调返回的对象,就会作为execute本身的返回值
            return null;
        });
        redisTemplate.opsForList().leftPush("key", "111");
        redisTemplate.opsForList().rightPush("key", "222");
        String value = redisTemplate.opsForList().rightPop("key");
        System.out.println("value:" + value);
        value = redisTemplate.opsForList().leftPop("key");
        System.out.println("value:" + value);
        return "OK";
    }
 
    @GetMapping("/testSet")
    @ResponseBody
    public String testSet() {
        redisTemplate.execute((RedisConnection connecion) -> {
            connecion.flushAll();
            return null;
        });
        redisTemplate.opsForSet().add("key", "111", "222", "333");
        Set<String> result = redisTemplate.opsForSet().members("key");
        System.out.println("result:" + result);
        boolean exists = redisTemplate.opsForSet().isMember("key", "111");
        System.out.println("exist:" + exists);
        Long count = redisTemplate.opsForSet().size("key");
        System.out.println("count:" + count);
        redisTemplate.opsForSet().remove("key", "111", "222");
        result = redisTemplate.opsForSet().members("key");
        System.out.println("result:" + result);
        return "Ok";
    }
    @GetMapping("/testHash")
    @ResponseBody
    public String testHash(){
        redisTemplate.execute((RedisConnection connection)->{
            connection.flushAll();
            return  null;
                });
                redisTemplate.opsForHash().put("key","f1","111");
                redisTemplate.opsForHash().put("key","f2","222");
                redisTemplate.opsForHash().put("key","f3","333");
                String value= (String)  redisTemplate.opsForHash().get("key","f1");
                Boolean exists=redisTemplate.opsForHash().hasKey("key","f1");
                System.out.println("exists:"+exists);
                redisTemplate.opsForHash().delete("key","f1","f2");
                Long size=redisTemplate.opsForHash().size("key");
                System.out.println("size"+size);
                return "OK";
    }
 
    @GetMapping("/testZSet")
    @ResponseBody
    public String testZSet(){
        redisTemplate.execute((RedisConnection connection)->{
            connection.flushAll();
            return null;
        });
        redisTemplate.opsForZSet().add("key","zhangsan",10);
        redisTemplate.opsForZSet().add("key","lisi",20);
        redisTemplate.opsForZSet().add("key","wangwu",30);
        Set<String>members= redisTemplate.opsForZSet().range("key",0,-1);
        System.out.println("members:"+members);
 
        Set<ZSetOperations.TypedTuple<String>>membersWithScore=redisTemplate.opsForZSet().rangeWithScores("key",0,-1);
        System.out.println("membersWithScore:"+membersWithScore);
 
        Double score= redisTemplate.opsForZSet().score("key","zhangsan");
        System.out.println("score:"+score);
 
        redisTemplate.opsForZSet().remove("key","zhangsan");
        Long size=redisTemplate.opsForZSet().size("key");
        System.out.println("size:"+size);
 
        Long rank=redisTemplate.opsForZSet().rank("key","lisi");
        System.out.println("rank:"+rank);
        return "OK";
    }
}


相关实践学习
基于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
相关文章
|
10天前
|
NoSQL Java 应用服务中间件
蓝易云 - Spring redis使用报错Read timed out排查解决
以上都是可能的解决方案,具体的解决方案可能会因具体情况而异。
15 1
|
6天前
|
缓存 NoSQL Java
Spring Boot整合Redis缓存的最佳实践
Spring Boot整合Redis缓存的最佳实践
|
9天前
|
缓存 NoSQL Java
Spring Boot与Redis集成的最佳实践
Spring Boot与Redis集成的最佳实践
|
9天前
|
缓存 NoSQL Java
Spring Boot与Redis的缓存一致性问题
Spring Boot与Redis的缓存一致性问题
|
9天前
|
缓存 NoSQL Java
Spring Boot整合Redis缓存的最佳实践
Spring Boot整合Redis缓存的最佳实践
|
9天前
|
消息中间件 NoSQL Java
Spring Boot中使用Redis和Lua脚本实现延时队列
Spring Boot中使用Redis和Lua脚本实现延时队列
|
10天前
|
缓存 NoSQL Java
Spring Boot2 系列教程(二十九)Spring Boot 整合 Redis
Spring Boot2 系列教程(二十九)Spring Boot 整合 Redis
|
存储 缓存 NoSQL
Redis 缓存 + Spring 的集成示例
SpringSession和Redis实现Session跨域 http://www.ithao123.cn/content-11111681.html   tomcat中创建session很耗服务器内存 原生session与session in redis对比下面是从stackoverflo...
1360 0
|
存储 缓存 NoSQL
Redis 缓存 + Spring 的集成示例(转)
《整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 Spring MVC、IOC、MyBatis ORM 三者的整合以及声明式事务处理。
1428 0