Java中Redis常用的API及其对应的原始API

相信大家写redis的时候经常忘记一些指令吧[狗头][狗头],这里整理了一下

一、 String(字符串类型)

1.代码块
// 设置字符串值
stringRedisTemplate.opsForValue().set("key", "value");
// Redis: SET key value// 设置值并设置过期时间(60秒)
stringRedisTemplate.opsForValue().set("key", "value", Duration.ofSeconds(60));
// Redis: SETEX key 60 value// 获取值
String value = stringRedisTemplate.opsForValue().get("key");
// Redis: GET key// 删除键
Boolean isDeleted = stringRedisTemplate.delete("key");
// Redis: DEL key// 判断键是否存在
Boolean exists = stringRedisTemplate.hasKey("key");
// Redis: EXISTS key// 如果键不存在则设置(SETNX)
Boolean successIfAbsent = stringRedisTemplate.opsForValue().setIfAbsent("key", "value");
// Redis: SETNX key value// 如果键存在则设置(SETXX)
Boolean successIfPresent = stringRedisTemplate.opsForValue().setIfPresent("key", "value");
// Redis: SET key value XX// 批量设置多个键值对
Map<String, String> bulkData = new HashMap<>();
bulkData.put("k1", "v1");
bulkData.put("k2", "v2");
stringRedisTemplate.opsForValue().multiSet(bulkData);
// Redis: MSET k1 v1 k2 v2// 批量获取多个键的值
List<String> values = stringRedisTemplate.opsForValue().multiGet(Arrays.asList("k1", "k2"));
// Redis: MGET k1 k2// 自增操作(值必须为整数)
Long newValueAfterIncr = stringRedisTemplate.opsForValue().increment("key");
// Redis: INCR key// 自增指定数值
Long newValueAfterIncrBy = stringRedisTemplate.opsForValue().increment("key", 5);
// Redis: INCRBY key 5// 自减操作(值必须为整数)
Long newValueAfterDecr = stringRedisTemplate.opsForValue().decrement("key");
// Redis: DECR key// 自减指定数值
Long newValueAfterDecrBy = stringRedisTemplate.opsForValue().decrement("key", 3);
// Redis: DECRBY key 3// 获取旧值并设置新值
String oldVal = stringRedisTemplate.opsForValue().getAndSet("key", "newVal");
// Redis: GETSET key newVal// 设置键的过期时间(30秒)
Boolean expireSuccess = stringRedisTemplate.expire("key", Duration.ofSeconds(30));
// Redis: EXPIRE key 30// 获取键的剩余生存时间(TTL)
Long ttl = stringRedisTemplate.getExpire("key");
// Redis: TTL key// 移除键的过期时间(持久化)
Boolean persistSuccess = stringRedisTemplate.persist("key");
// Redis: PERSIST key// 截取字符串的一部分
String range = stringRedisTemplate.opsForValue().get("key", 0, 5);
// Redis: GETRANGE key 0 5// 替换字符串中指定偏移位置的内容
stringRedisTemplate.opsForValue().set("key", "insert", 2);
// Redis: SETRANGE key 2 insert
2.表格
操作Java API返回类型Redis 命令
设置值stringRedisTemplate.opsForValue().set("key", "value")voidSET key value
设置值并过期stringRedisTemplate.opsForValue().set("key", "value", Duration.ofSeconds(60))voidSETEX key 60 value
获取值stringRedisTemplate.opsForValue().get("key")StringGET key
删除键stringRedisTemplate.delete("key")BooleanDEL key
判断是否存在stringRedisTemplate.hasKey("key")BooleanEXISTS key
设置值如果不存在(SETNX)stringRedisTemplate.opsForValue().setIfAbsent("key", "value")BooleanSETNX key value
设置值如果存在(SETXX)stringRedisTemplate.opsForValue().setIfPresent("key", "value")BooleanSET key value XX
批量设置值stringRedisTemplate.opsForValue().multiSet(map)voidMSET k1 v1 k2 v2
批量获取值stringRedisTemplate.opsForValue().multiGet(Arrays.asList("k1", "k2"))List<String>MGET k1 k2
自增stringRedisTemplate.opsForValue().increment("key")LongINCR key
自增指定值stringRedisTemplate.opsForValue().increment("key", 5)LongINCRBY key 5
自减stringRedisTemplate.opsForValue().decrement("key")LongDECR key
自减指定值stringRedisTemplate.opsForValue().decrement("key", 3)LongDECRBY key 3
获取旧值并设置新值stringRedisTemplate.opsForValue().getAndSet("key", "newVal")StringGETSET key newVal
设置过期时间stringRedisTemplate.expire("key", Duration.ofSeconds(30))BooleanEXPIRE key 30
获取剩余 TTLstringRedisTemplate.getExpire("key")DurationTTL key
持久化(去掉过期时间)stringRedisTemplate.persist("key")BooleanPERSIST key
截取字符串stringRedisTemplate.opsForValue().get("key", 0, 5)StringGETRANGE key 0 5
替换指定位置的字符串stringRedisTemplate.opsForValue().set("key", "abc", 2)voidSETRANGE key 2 abc

二、List(列表类型)

1.代码块
// 左侧插入元素(头插)
Long sizeAfterLeftPush = stringRedisTemplate.opsForList().leftPush("list", "a");
// Redis: LPUSH list a// 右侧插入元素(尾插)
Long sizeAfterRightPush = stringRedisTemplate.opsForList().rightPush("list", "b");
// Redis: RPUSH list b// 左侧弹出元素(头删)
String leftPopValue = stringRedisTemplate.opsForList().leftPop("list");
// Redis: LPOP list// 右侧弹出元素(尾删)
String rightPopValue = stringRedisTemplate.opsForList().rightPop("list");
// Redis: RPOP list// 阻塞式左侧弹出元素(等待最多10秒)
String blockedLeftPop = stringRedisTemplate.opsForList().leftPop("list", Duration.ofSeconds(10));
// Redis: BLPOP list 10// 获取列表指定范围内的元素(0 到 -1 表示全部)
List<String> elements = stringRedisTemplate.opsForList().range("list", 0, -1);
// Redis: LRANGE list 0 -1// 获取列表长度
Long listSize = stringRedisTemplate.opsForList().size("list");
// Redis: LLEN list// 设置指定索引位置的值
stringRedisTemplate.opsForList().set("list", 1, "newVal");
// Redis: LSET list 1 newVal// 删除指定值的元素(删除第一个等于 "val" 的元素)
Long removedCount = stringRedisTemplate.opsForList().remove("list", 1, "val");
// Redis: LREM list 1 val
2.表格
操作Java API返回类型Redis 命令
左入队stringRedisTemplate.opsForList().leftPush("list", "a")LongLPUSH list a
右入队stringRedisTemplate.opsForList().rightPush("list", "b")LongRPUSH list b
左出队stringRedisTemplate.opsForList().leftPop("list")StringLPOP list
右出队stringRedisTemplate.opsForList().rightPop("list")StringRPOP list
阻塞左出队stringRedisTemplate.opsForList().leftPop("list", Duration.ofSeconds(10))StringBLPOP list 10
获取范围内元素stringRedisTemplate.opsForList().range("list", 0, -1)List<String>LRANGE list 0 -1
获取列表长度stringRedisTemplate.opsForList().size("list")LongLLEN list
设置指定位置的值stringRedisTemplate.opsForList().set("list", 1, "newVal")voidLSET list 1 newVal
删除指定元素stringRedisTemplate.opsForList().remove("list", 1, "val")LongLREM list 1 val

三、Hash(哈希类型)

1.代码块
// 设置字段值
stringRedisTemplate.opsForHash().put("hash", "field", "val");
// Redis: HSET hash field val// 获取字段值
Object fieldValue = stringRedisTemplate.opsForHash().get("hash", "field");
// Redis: HGET hash field// 获取所有字段和值
Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("hash");
// Redis: HGETALL hash// 获取所有字段名
Set<Object> keys = stringRedisTemplate.opsForHash().keys("hash");
// Redis: HKEYS hash// 获取所有字段值
List<Object> values = stringRedisTemplate.opsForHash().values("hash");
// Redis: HVALS hash// 判断字段是否存在
Boolean hasField = stringRedisTemplate.opsForHash().hasKey("hash", "field");
// Redis: HEXISTS hash field// 删除字段
Long deletedCount = stringRedisTemplate.opsForHash().delete("hash", "field");
// Redis: HDEL hash field// 批量设置字段值
Map<String, String> map = new HashMap<>();
map.put("field1", "value1");
map.put("field2", "value2");
stringRedisTemplate.opsForHash().putAll("hash", map);
// Redis: HMSET hash field1 value1 field2 value2// 批量获取字段值
List<Object> multiGetValues = stringRedisTemplate.opsForHash().multiGet("hash", Arrays.asList("field1", "field2"));
// Redis: HMGET hash field1 field2// 字段值自增(数值必须为整数)
Long incrementedValue = stringRedisTemplate.opsForHash().increment("hash", "field", 1L);
// Redis: HINCRBY hash field 1
2.表格
操作Java API返回类型Redis 命令
设置字段值stringRedisTemplate.opsForHash().put("hash", "field", "val")voidHSET hash field val
获取字段值stringRedisTemplate.opsForHash().get("hash", "field")ObjectHGET hash field
获取所有字段stringRedisTemplate.opsForHash().entries("hash")Map<Object, Object>HGETALL hash
获取所有字段名stringRedisTemplate.opsForHash().keys("hash")Set<Object>HKEYS hash
获取所有字段值stringRedisTemplate.opsForHash().values("hash")List<Object>HVALS hash
判断字段是否存在stringRedisTemplate.opsForHash().hasKey("hash", "field")BooleanHEXISTS hash field
删除字段stringRedisTemplate.opsForHash().delete("hash", "field")LongHDEL hash field
批量设置字段值stringRedisTemplate.opsForHash().putAll("hash", map)voidHMSET hash field1 val1 ...
批量获取字段值stringRedisTemplate.opsForHash().multiGet("hash", Arrays.asList("f1", "f2"))List<Object>HMGET hash f1 f2
字段值自增stringRedisTemplate.opsForHash().increment("hash", "field", 1)LongHINCRBY hash field 1

四、Set(集合类型)

1.代码块
// 添加元素到集合
Long addCount = stringRedisTemplate.opsForSet().add("set", "a");
// Redis: SADD set a// 删除集合中的元素
Long removeCount = stringRedisTemplate.opsForSet().remove("set", "a");
// Redis: SREM set a// 判断某个元素是否存在于集合中
Boolean isMember = stringRedisTemplate.opsForSet().isMember("set", "a");
// Redis: SISMEMBER set a// 获取集合中的所有成员
Set<String> members = stringRedisTemplate.opsForSet().members("set");
// Redis: SMEMBERS set// 获取集合的元素个数
Long setSize = stringRedisTemplate.opsForSet().size("set");
// Redis: SCARD set// 随机弹出一个元素(并从集合中删除)
String poppedElement = stringRedisTemplate.opsForSet().pop("set");
// Redis: SPOP set// 随机获取一个元素(不删除)
String randomElement = stringRedisTemplate.opsForSet().randomMember("set");
// Redis: SRANDMEMBER set
2.表格
操作Java API返回类型Redis 命令
添加元素stringRedisTemplate.opsForSet().add("set", "a")LongSADD set a
删除元素stringRedisTemplate.opsForSet().remove("set", "a")LongSREM set a
判断是否存在stringRedisTemplate.opsForSet().isMember("set", "a")BooleanSISMEMBER set a
获取所有元素stringRedisTemplate.opsForSet().members("set")Set<String>SMEMBERS set
获取元素个数stringRedisTemplate.opsForSet().size("set")LongSCARD set
随机弹出一个元素stringRedisTemplate.opsForSet().pop("set")StringSPOP set
随机获取一个元素(不删除)stringRedisTemplate.opsForSet().randomMember("set")StringSRANDMEMBER set

五、ZSet(有序集合)

1.代码块
// 添加元素及分数
Boolean addSuccess = stringRedisTemplate.opsForZSet().add("zset", "member", 100);
// Redis: ZADD zset 100 member// 删除元素
Long removeCount = stringRedisTemplate.opsForZSet().remove("zset", "member");
// Redis: ZREM zset member// 获取成员的排名(按分数升序)
Long rank = stringRedisTemplate.opsForZSet().rank("zset", "member");
// Redis: ZRANK zset member// 获取成员的排名(按分数降序)
Long reverseRank = stringRedisTemplate.opsForZSet().reverseRank("zset", "member");
// Redis: ZREVRANK zset member// 获取成员的分数
Double score = stringRedisTemplate.opsForZSet().score("zset", "member");
// Redis: ZSCORE zset member// 增加成员的分数
Double newScore = stringRedisTemplate.opsForZSet().incrementScore("zset", "member", 5);
// Redis: ZINCRBY zset 5 member// 获取指定范围内的成员(按分数升序,索引 0 到 10)
Set<String> rangeMembers = stringRedisTemplate.opsForZSet().range("zset", 0, 10);
// Redis: ZRANGE zset 0 10// 获取指定范围内的成员(按分数降序,索引 0 到 10)
Set<String> reverseRangeMembers = stringRedisTemplate.opsForZSet().reverseRange("zset", 0, 10);
// Redis: ZREVRANGE zset 0 10
2.表格
操作Java API返回类型Redis 命令
添加元素及分数stringRedisTemplate.opsForZSet().add("zset", "member", 100)BooleanZADD zset 100 member
删除元素stringRedisTemplate.opsForZSet().remove("zset", "member")LongZREM zset member
获取排名(正序)stringRedisTemplate.opsForZSet().rank("zset", "member")LongZRANK zset member
获取排名(倒序)stringRedisTemplate.opsForZSet().reverseRank("zset", "member")LongZREVRANK zset member
获取成员分数stringRedisTemplate.opsForZSet().score("zset", "member")DoubleZSCORE zset member
增加分数stringRedisTemplate.opsForZSet().incrementScore("zset", "member", 5)DoubleZINCRBY zset 5 member
获取指定范围(正序)stringRedisTemplate.opsForZSet().range("zset", 0, 10)Set<String>ZRANGE zset 0 10
获取指定范围(倒序)stringRedisTemplate.opsForZSet().reverseRange("zset", 0, 10)Set<String>ZREVRANGE zset 0 10

六、BitMap(位图)

1.代码块
// 设置指定偏移位的 bit 值为 1
stringRedisTemplate.opsForValue().setBit("bitmap", 1, true);
// Redis: SETBIT bitmap 1 1// 获取指定偏移位的 bit 值
Boolean bit = stringRedisTemplate.opsForValue().getBit("bitmap", 1);
// Redis: GETBIT bitmap 1// 统计所有为 1 的 bit 数量
Long count = stringRedisTemplate.execute((RedisConnection connection) ->connection.bitCount("bitmap".getBytes()));
// Redis: BITCOUNT bitmap// 对两个 bitmap 做 AND 运算并将结果保存到新 key
Long resultLength = stringRedisTemplate.execute((RedisConnection connection) ->connection.bitOpAnd("result".getBytes(), "bitmap1".getBytes(), "bitmap2".getBytes()));
// Redis: BITOP AND result bitmap1 bitmap2// 获取 bitmap 底层字符串的字节长度(即占用多少字节)
Long size = stringRedisTemplate.opsForValue().size("bitmap");
// Redis: STRLEN bitmap// 获取 bitmap 的某段二进制范围(可用于分页或分析)
String partial = stringRedisTemplate.opsForValue().get("bitmap", 0, 5);
// Redis: GETRANGE bitmap 0 5
2.表格
操作Java API返回类型Redis 命令
设置指定偏移位的 bit 值(1 或 0)stringRedisTemplate.opsForValue().setBit("bitmap", 1, true)BooleanSETBIT bitmap 1 1
获取指定偏移位的 bit 值stringRedisTemplate.opsForValue().getBit("bitmap", 1)BooleanGETBIT bitmap 1
统计所有为 1 的 bit 数量(位数统计)stringRedisTemplate.execute((RedisConnection connection) -> connection.bitCount("bitmap".getBytes()));LongBITCOUNT bitmap
对多个 bitmap 做位运算(AND/OR/XOR/NOT)并保存结果stringRedisTemplate.execute((RedisConnection connection) -> connection.bitOpAnd("dest".getBytes(), "bitmap1".getBytes(), "bitmap2".getBytes()));LongBITOP AND dest bitmap1 bitmap2
获取 bitmap 占用的字节数(即底层字符串长度)stringRedisTemplate.opsForValue().size("bitmap")LongSTRLEN bitmap
获取 bitmap 指定范围内的二进制数据(可用来做分页处理)stringRedisTemplate.opsForValue().get("bitmap", offsetStart, offsetEnd)StringGETRANGE bitmap offset_start offset_end
执行位运算后返回结果(不保存)stringRedisTemplate.execute((RedisConnection connection) -> connection.bitOp(BitOperation.OR, null, key1.getBytes(), key2.getBytes()))byte[]BITOP OR dest key1 key2

七、HyperLogLog

1.代码块
// 添加单个元素到 HyperLogLog
Long addResult = stringRedisTemplate.opsForHyperLogLog().add("hll", "val1");
// Redis: PFADD hll val1// 添加多个元素到 HyperLogLog
Long addMultiResult = stringRedisTemplate.opsForHyperLogLog().add("hll", new String[]{"val1", "val2", "val3"});
// Redis: PFADD hll val1 val2 val3// 获取 HyperLogLog 中估算的唯一元素数量(基数估计值)
Long size = stringRedisTemplate.opsForHyperLogLog().size("hll");
// Redis: PFCOUNT hll// 合并多个 HyperLogLog 到一个新的 HyperLogLog 中
stringRedisTemplate.opsForHyperLogLog().union("hllUnion", new String[]{"hll1", "hll2"});
// Redis: PFMERGE hllUnion hll1 hll2// 获取合并后 HyperLogLog 中估算的唯一元素数量
Long unionSize = stringRedisTemplate.opsForHyperLogLog().size("hllUnion");
// Redis: PFCOUNT hllUnion// 对多个 HyperLogLog 进行基数估计,无需显式合并
Long multiCount = stringRedisTemplate.opsForHyperLogLog().size(new String[]{"hll1", "hll2"});
// Redis: PFCOUNT hll1 hll2
2.表格
操作Java API返回类型Redis 命令
添加单个元素stringRedisTemplate.opsForHyperLogLog().add("hll", "val1")LongPFADD hll val1
添加多个元素stringRedisTemplate.opsForHyperLogLog().add("hll", new String[]{"val1", "val2"})LongPFADD hll val1 val2
获取基数估计值(单个)stringRedisTemplate.opsForHyperLogLog().size("hll")LongPFCOUNT hll
获取多个 HLL 的合并基数估计值stringRedisTemplate.opsForHyperLogLog().size(new String[]{"hll1", "hll2"})LongPFCOUNT hll1 hll2
合并多个 HLL 到新 HLLstringRedisTemplate.opsForHyperLogLog().union("hllUnion", new String[]{"hll1", "hll2"})LongPFMERGE hllUnion hll1 hll2

八、GEO(地理位置)

1.代码块
// 添加地理位置
Long addResult = stringRedisTemplate.opsForGeo().add("geo", new Point(116.40, 39.90), "beijing");
// Redis: GEOADD geo 116.40 39.90 beijing// 获取两个位置之间的距离,默认单位为米
Distance distance = stringRedisTemplate.opsForGeo().distance("geo", "beijing", "shanghai");
// Redis: GEODIST geo beijing shanghai// 获取指定地点周围一定范围内的位置(例如:以北京为中心,半径100公里)
Circle circle = new Circle(new Point(116.40, 39.90), new Distance(100, Metrics.KILOMETERS));
GeoResults<RedisGeoCommands.GeoLocation<String>> nearbyPlaces = stringRedisTemplate.opsForGeo().radius("geo", circle);
// Redis: GEORADIUS geo 116.40 39.90 100 km// 获取某个位置的经纬度坐标
List<Point> points = stringRedisTemplate.opsForGeo().position("geo", "beijing");
// Redis: GEOPOS geo beijing
2.表格
操作Java API返回类型Redis 命令
添加地理位置stringRedisTemplate.opsForGeo().add("geo", new Point(116.40, 39.90), "beijing")LongGEOADD geo 116.40 39.90 beijing
获取两个位置距离stringRedisTemplate.opsForGeo().distance("geo", "beijing", "shanghai")DistanceGEODIST geo beijing shanghai
获取某地附近的位置stringRedisTemplate.opsForGeo().radius("geo", new Circle(new Point(116.40, 39.90), new Distance(100, Metrics.KILOMETERS)))

GeoResults

<RedisGeoCommands.

GeoLocation<String>>

GEORADIUS geo 116.40 39.90 100 km
获取位置经纬度stringRedisTemplate.opsForGeo().position("geo", "beijing")List<Point>GEOPOS geo beijing

九、Stream(流)

1.代码块
// 添加记录到 Stream 中
Map<String, String> map = new HashMap<>();
map.put("field1", "val1");
RecordId recordId = stringRedisTemplate.opsForStream().add("mystream", map);
// Redis: XADD mystream * field1 val1// 读取 Stream 中的记录
List<MapRecord<String, Object, Object>> records = stringRedisTemplate.opsForStream().read(StreamReadOptions.empty().count(1),StreamOffset.fromStart("mystream"));
// Redis: XRANGE mystream - + COUNT 1// 创建消费者组
try {stringRedisTemplate.opsForStream().createGroup("mystream", ReadOffset.latest(), "mygroup");
} catch (Exception e) {// 可能会抛出异常如果组已存在
}
// Redis: XGROUP CREATE mystream mygroup $ MKSTREAM// 使用消费者组读取 Stream 中的新消息
List<MapRecord<String, Object, Object>> groupRecords = stringRedisTemplate.opsForStream().read(Consumer.from("mygroup", "consumer1"),StreamReadOptions.empty(),StreamOffset.create("mystream", ReadOffset.lastConsumed()));
// Redis: XREADGROUP GROUP mygroup consumer1 STREAMS mystream >
2.表格
操作Java API返回类型Redis 命令
添加记录stringRedisTemplate.opsForStream().add("mystream", map)RecordIdXADD mystream * field1 val1
读取记录stringRedisTemplate.opsForStream().read(StreamReadOptions.empty().count(1), StreamOffset.fromStart("mystream"))List<MapRecord<String, Object, Object>>XRANGE mystream - + COUNT 1
创建消费者组stringRedisTemplate.opsForStream().createGroup("mystream", ReadOffset.latest(), "mygroup")voidXGROUP CREATE mystream mygroup $ MKSTREAM
消费组读取stringRedisTemplate.opsForStream().read(Consumer.from("mygroup", "consumer1"), StreamReadOptions.empty(), StreamOffset.create("mystream", ReadOffset.lastConsumed()))List<MapRecord<String, Object, Object>>

XREADGROUP GROUP mygroup consumer1 STREAMS mystream >

十、管道批次化工具类

 

package com.quick.utils;import com.quick.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;/*** @program: quick-pick* @description: redis 管道批量操作* @author: bluefoxyu* @date: 2025-06-17 00:14**/@Slf4j
public class RedisPipelineUtil {/*** 批量执行 Redis 管道操作,固定先删除旧 key,再新增内容,再设置过期时间,带异常捕获和清理。 TODO 这个只做参考案例不做调用** @param stringRedisTemplate Redis 操作模板* @param dataList            需要批量操作的数据集合* @param keyPrefix           Redis key 前缀(用作拼接 key)*                            你操作时先 del,再 add(或其它写操作),再 expire* @param <T>                 数据类型泛型*/public static <T> void batchDelAddExpire(StringRedisTemplate stringRedisTemplate,List<T> dataList,String keyPrefix) {if (dataList == null || dataList.isEmpty()) {return;}try {Object object =new Object(); // 需要存的数据// 一次性stringRedisTemplate.executePipelined((RedisCallback<Object>) connection -> {for (T fav : dataList) {long userId = 1L; // 用户ID用于拼接 TODO 实际上业务场景中得从dataList的fav中取出来,删除对应用户的String redisKey = keyPrefix + userId;// 先删除原来的 Redis 数据connection.del(redisKey.getBytes());// 这个 .getBytes() 是为了把字符串转换成字节数组(byte[]),因为底层 Redis 连接的 API 需要的是字节数组作为参数。connection.sAdd(redisKey.getBytes(), object.toString().getBytes());// 3. 设置随机过期时间防雪崩connection.expire(redisKey.getBytes(),TimeUnit.DAYS.toSeconds(7) + ThreadLocalRandom.current().nextInt(86400));}return null;});// 分批次int batchSize = 100;for (int i = 0; i < dataList.size(); i += batchSize) {List<T> batch = dataList.subList(i, Math.min(i + batchSize, dataList.size()));stringRedisTemplate.executePipelined((RedisCallback<?>) connection -> {for (T fav : batch) {// 执行操作}return null;});}} catch (Exception ex) {log.error("将数据放进Redis任务异常", ex);} finally {// 清理集合,加速 GCdataList.clear();}}/*** 使用 StringRedisTemplate 按 key 模式批量删除 Redis 键** @param stringRedisTemplate 注入的 StringRedisTemplate* @param keyPattern 通配符模式,如 "user:session:*"* @param batchSize 每批删除的 key 数量*/public static void batchDeleteByPattern(StringRedisTemplate stringRedisTemplate, String keyPattern, int batchSize) {// 构建 scan 配置,支持模糊匹配 + 每批数量控制ScanOptions options = ScanOptions.scanOptions().match(keyPattern).count(batchSize).build();try (Cursor<byte[]> cursor = Objects.requireNonNull(stringRedisTemplate.getConnectionFactory()).getConnection().scan(options)) {List<String> keys = new ArrayList<>(batchSize);while (cursor.hasNext()) {// 将 byte[] 转成 String keyString key = stringRedisTemplate.getStringSerializer().deserialize(cursor.next());if (key != null) {keys.add(key);}// 每达到一批就批量删除if (keys.size() >= batchSize) {stringRedisTemplate.delete(keys);keys.clear();}}// 删除最后不足一批的if (!keys.isEmpty()) {stringRedisTemplate.delete(keys);}} catch (Exception e) {System.err.println("Redis 扫描删除异常: " + e.getMessage());throw new BaseException("Redis 扫描删除异常, 异常信息为:" + e.getMessage());}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/bicheng/85156.shtml
繁体地址,请注明出处:http://hk.pswp.cn/bicheng/85156.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C#使用ExcelDataReader高效读取excel文件写入数据库

分享一个库ExcelDataReader &#xff0c;它专注读取、支持 .xls/.xlsx、内存优化。 首先安装NuGet 包 dotnet add package ExcelDataReader dotnet add package System.Text.Encoding.CodePages 编码 内存优化​​&#xff1a;每次仅读取一行&#xff0c;适合处理百万级数据…

雪豹速清APP:高效清理,畅享流畅手机体验

在智能手机的日常使用中&#xff0c;随着时间的推移&#xff0c;手机中会积累大量的垃圾文件&#xff0c;如临时文件、缓存数据、无用的安装包等。这些垃圾文件不仅会占用宝贵的存储空间&#xff0c;还会导致手机运行缓慢&#xff0c;甚至出现卡顿现象。为了解决这一问题&#…

关于使用v-bind绑定多个属性值的问题

背景。自定义表单开发。属性值过多&#xff0c;都写死很臃肿而且不方便维护。通过v-bind绑定非常方便。但是问题又来了。改以怎样的方式处理呢。返回值的格式需要注意 下面是两张动态处理v-bind属性的方法。第一张是写在了方法里面&#xff0c;第二张使用了虚拟属性。使用虚拟…

基于CNN的FashionMNIST数据集识别6——DenseNet模型

源码 import torch from torch import nn from torchsummary import summary""" DenseNet的核心组件&#xff1a;稠密层(DenseLayer) 实现特征复用机制&#xff0c;每个层的输出会与所有前序层的输出在通道维度拼接 """class DenseLayer(nn.Mod…

MySQL 中 INSERT ... ON DUPLICATE KEY UPDATE 为什么会导致主键自增失效?

最近开发的过程中&#xff0c;使用ai生成代码&#xff0c;写了一条这样的SQL&#xff1a;INSERT … ON DUPLICATE KEY UPDATE&#xff0c;然后发现一个奇怪的现象&#xff1a; 为什么使用这个语法后&#xff0c;自增主键&#xff08;AUTO_INCREMENT&#xff09;的值会跳跃甚至…

jenkins流水线打包vue无权限

jenkins在使用npm命令进行拉取依赖时,创建目录会报错无权限&#xff0c;如下如所示 这是因为npm 出于安全考虑不支持以 root 用户运行&#xff0c;即使你用 root 用户身份运行了&#xff0c;npm 会自动转成一个叫 nobody 的用户来运行&#xff0c;而这个用户权限非常低 若需要…

快速实现golang的grpc服务

文章目录 1、安装服务2、检查安装版本情况3、编写proto文件4、生成代码5、实现业务逻辑6、创建provider7、测试调用 1、安装服务 1、protoc安装 需去官网下载 protobuf 2、命令行安装protoc-gen-go和protoc-gen-go-grpc $ go install google.golang.org/protobuf/cmd/protoc-…

C++ 学习 多线程 2025年6月17日18:41:30

多线程(标准线程库 <thread>) 创建线程 #include <iostream> #include <thread>void hello() {std::cout << "Hello from thread!\n"; }int main() {// 创建线程并执行 hello() std::thread t(hello); //线程对象&#xff0c;传入可调用对…

常见的测试工具及分类

Web测试工具是保障Web应用质量的核心支撑&#xff0c;根据测试类型&#xff08;功能、性能、安全、自动化等&#xff09;和场景需求&#xff0c;可分为多个类别。以下从​​八大核心测试类型​​出发&#xff0c;梳理常见工具及其特点、适用场景&#xff1a; ​​一、功能测试工…

七牛存储sdk在springboot完美集成和应用 七牛依赖 自动化配置

文章目录 概要依赖配置属性配置类配置文件业务层控制层运行结果亮点 概要 七牛存储很便宜的&#xff0c;在使用项目的用好官方封装好的sdk&#xff0c;结合springboot去使用很方便&#xff0c;我本地用的是springoot3spring-boot-autoconfigure 依赖 <dependency><…

Java相关-链表-设计链表-力扣707

你可以选择使用单链表或者双链表&#xff0c;设计并实现自己的链表。 单链表中的节点应该具备两个属性&#xff1a;val 和 next 。val 是当前节点的值&#xff0c;next 是指向下一个节点的指针/引用。 如果是双向链表&#xff0c;则还需要属性 prev 以指示链表中的上一个节点…

C# 关于LINQ语法和类型的使用

常用语法&#xff0c;具体问题具体分析 1. Select2. SelectMany3. Where4. Take5. TakeWhile6. SkipWhile7. Join8. GroupJoin9. OrderBy10. OrderByDescending11. ThenBy12. Concat13. Zip14. Distinct15. Except16. Union17. Intersect18. Concat19. Reverse20. SequenceEqua…

华为OD-2024年E卷-小明周末爬山[200分] -- python

问题描述&#xff1a; 题目描述 周末小明准备去爬山锻炼&#xff0c;0代表平地&#xff0c;山的高度使用1到9来表示&#xff0c;小明每次爬山或下山高度只能相差k及k以内&#xff0c;每次只能上下左右一个方向上移动一格&#xff0c;小明从左上角(0,0)位置出发 输入描述 第一行…

Android:使用OkHttp

1、权限&#xff1a; <uses-permission android:name"android.permission.INTERNET" /> implementation com.squareup.okhttp3:okhttp:3.4.1 2、GET&#xff1a; new XXXTask ().execute("http://192.168.191.128:9000/xx");private class XXXTask…

Vue3+Element Plus动态表格列宽设置

在 Vue3 Element Plus 中实现动态设置表格列宽&#xff0c;可以通过以下几种方式实现&#xff1a; 方法 1&#xff1a;动态绑定 width 属性&#xff08;推荐&#xff09; vue 复制 下载 <template><el-table :data"tableData" style"width: 100%…

【JVM目前使用过的参数总结】

JVM参数总结 笔记记录 JVM-栈相关JVM-方法区(元空间)相关JVM-堆相关 JVM-栈相关 .-XX:ThreadStackSize1M -Xss1m 上面的简写形式【设置栈的大小】 JVM-方法区(元空间)相关 -XX:MaxMetaspaceSize10m 【设置最大元空间大小】 JVM-堆相关 -XX:MaxHeapSize10m -Xmx10m 上面的简写形…

AI辅助高考志愿填报-专业全景解析与报考指南

高考志愿填报&#xff0c;这可是关系到孩子未来的大事儿&#xff01;最近&#xff0c;我亲戚家的孩子也面临着这个难题&#xff0c;昨晚一个电话就跟我聊了好久&#xff0c;问我报啥专业好。说实话&#xff0c;这问题真不好回答&#xff0c;毕竟每个孩子情况不一样&#xff0c;…

Android Studio Windows安装与配置指南

Date: 2025-06-14 20:07:12 author: lijianzhan 内容简介 文章中&#xff0c;主要是为了初次接触 Android 开发的用户提供详细的关于 Android Studio 安装以及配置教程&#xff0c;涵盖环境准备、软件下载、安装配置全流程&#xff0c;重点解决路径命名、组件选择、工作空间设置…

SpringAI+DeepSeek-了解AI和大模型应用

一、认识AI 1.人工智能发展 AI&#xff0c;人工智能&#xff08;Artificial Intelligence&#xff09;&#xff0c;使机器能够像人类一样思考、学习和解决问题的技术。 AI发展至今大概可以分为三个阶段&#xff1a; 其中&#xff0c;深度学习领域的自然语言处理(Natural Lan…

IP5362至为芯支持无线充的22.5W双C口双向快充移动电源方案芯片

英集芯IP5362是一款应用于移动电源&#xff0c;充电宝&#xff0c;手机&#xff0c;平板电脑等支持无线充模式的22.5W双向快充移动电源方案SOC芯片,集成同步升降压转换器、锂电池充电管理、电池电量指示等功能。兼容全部快充协议&#xff0c;同步开关放电支持最大22.5W输出功率…