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
英文地址,請注明出處:http://en.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輸出功率…