RedisTemplate操作Redis, 看这一篇文章就够了

文章目录



在这里插入图片描述

在这里插入图片描述

RedisTemplateSpring Framework 提供的用于操作 Redis 数据库的模板类。通过 RedisTemplate,开发人员可以方便地使用 Spring 提供的 API 来对 Redis 进行操作,比如设置值、获取值、删除值等。RedisTemplate 封装了 Redis 连接、数据序列化、异常处理等操作,简化了与 Redis 的交互过程。

一般情况下,开发人员需要配置 Redis 连接池、序列化器等信息,并将 RedisTemplate 注入到需要使用 Redis 的 Bean 中,然后就可以通过 RedisTemplate 来进行相应的操作。

需要注意的是,RedisTemplate 是基于 Spring Data Redis 提供的操作 Redis 客户端的功能而构建的,可以通过 RedisTemplate 李进行操作 Redis 数据库的常用数据结构,如字符串、列表、集合、有序集合等。


1. String 命令

1.1 添加缓存

//1、通过redisTemplate设置值
redisTemplate.boundValueOps("StringKey").set("StringValue");
redisTemplate.boundValueOps("StringKey").set("StringValue",1, TimeUnit.MINUTES);

//2、通过BoundValueOperations设置值
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
stringKey.set("StringVaule");
stringKey.set("StringValue",1, TimeUnit.MINUTES);

//3、通过ValueOperations设置值
ValueOperations ops = redisTemplate.opsForValue();
ops.set("StringKey", "StringVaule");
ops.set("StringValue","StringVaule",1, TimeUnit.MINUTES);

//4(SETNX + SETEX):这个key不存在执行 存在则不执行,多用于互斥锁
ops.setIfAbsent("key", "value", 10, TimeUnit.SECONDS)

1.2 设置过期时间(单独设置)

redisTemplate.boundValueOps("StringKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("StringKey",1,TimeUnit.MINUTES);

不建议使用单独设置过期时间的API, 可以使用 1.1 中的第一个演示,在设置值的同时设置过期时间.

1.3 获取缓存值

//1、通过redisTemplate设置值
String str1 = (String) redisTemplate.boundValueOps("StringKey").get();

//2、通过BoundValueOperations获取值
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
String str2 = (String) stringKey.get();

//3、通过ValueOperations获取值
ValueOperations ops = redisTemplate.opsForValue();
String str3 = (String) ops.get("StringKey");

1.4 删除key

Boolean result = redisTemplate.delete("key");

1.5 顺序递增

redisTemplate.boundValueOps("key").increment(1L);

该API会返回递增后的值. 如果KEY对应的值不存在会创建之并返回1

1.6 顺序递减

redisTemplate.boundValueOps("StringKey").increment(-3L);

1.7 常用的

ValueOperations ops = redisTemplate.opsForValue();

//	单独设置有效期(不推荐单独用)
ops.expire("StringKey",1,TimeUnit.MINUTES);

//	设置值 and 有效期(推荐这种)
ops.set("key", "value", 1, TimeUnit.MINUTES);

//	操作数值 增加 减少(INCR INCRBY)
ops.increment("key", 1);
ops.increment("key", -1);

//	(SETNX + SETEX):这个key不存在执行 存在则不执行,多用于互斥锁
ops.setIfAbsent("key", "value", 10, TimeUnit.SECONDS)

//	获取缓存值
ops.get("StringKey");

2. Hash命令

2.1 添加缓存

//
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值