系统过滤重复的请求

This commit is contained in:
2023-12-25 15:12:34 +08:00
parent 471f84af10
commit 894eccb186
3 changed files with 47 additions and 26 deletions

View File

@@ -8,7 +8,6 @@ import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
@@ -354,22 +353,33 @@ public class RedisCache {
*
* @param pattern 表达式abc*找出所有以abc开始的键
*/
public Set<String> scan(String pattern) {
return (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Set<String> keysTmp = new HashSet<>();
try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
.match(pattern)
.count(10000).build())) {
// public Set<String> scan(String pattern) {
// return (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
// Set<String> keysTmp = new HashSet<>();
// try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
// .match(pattern)
// .count(10000).build())) {
//
// while (cursor.hasNext()) {
// keysTmp.add(new String(cursor.next(), StandardCharsets.UTF_8));
// }
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// throw new RuntimeException(e);
// }
// return keysTmp;
// });
// }
while (cursor.hasNext()) {
keysTmp.add(new String(cursor.next(), StandardCharsets.UTF_8));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
return keysTmp;
});
/**
* setnx
* @param key 键
* @param value 值
* @param expireTime 过期时间,单位秒
* @return
*/
public Boolean setnx(String key, String value, long expireTime) {
return redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
}
/**
@@ -385,7 +395,7 @@ public class RedisCache {
//在一定时间内获取锁,超时则返回错误
for (; ; ) {
//Set命令返回OK则证明获取锁成功
Boolean ret = redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.SECONDS);
Boolean ret = setnx(lockKey, requestId, expireTime);
if (ret != null && ret) {
return true;
}