feat(cache/redisson): RedisUtils 新增限流方法

This commit is contained in:
2023-12-18 20:22:29 +08:00
parent cd6826a0ab
commit 9cf3ae87a1

View File

@@ -81,7 +81,7 @@ public class RedisUtils {
* 删除缓存
*
* @param key 键
* @return true 设置成功false 设置失败
* @return true设置成功false设置失败
*/
public static boolean delete(final String key) {
return CLIENT.getBucket(key).delete();
@@ -92,7 +92,7 @@ public class RedisUtils {
*
* @param key 键
* @param timeout 过期时间(单位:秒)
* @return true 设置成功false 设置失败
* @return true设置成功false设置失败
*/
public static boolean expire(final String key, final long timeout) {
return expire(key, Duration.ofSeconds(timeout));
@@ -103,7 +103,7 @@ public class RedisUtils {
*
* @param key 键
* @param duration 过期时间
* @return true 设置成功false 设置失败
* @return true设置成功false设置失败
*/
public static boolean expire(final String key, final Duration duration) {
return CLIENT.getBucket(key).expire(duration);
@@ -123,7 +123,7 @@ public class RedisUtils {
* 是否存在指定缓存
*
* @param key 键
* @return true 存在false 不存在
* @return true存在false不存在
*/
public static boolean hasKey(String key) {
RKeys keys = CLIENT.getKeys();
@@ -141,6 +141,21 @@ public class RedisUtils {
return stream.map(key -> getNameMapper().unmap(key)).collect(Collectors.toList());
}
/**
* 限流
*
* @param key 键
* @param rateType 限流类型OVERALL全局限流PER_CLIENT单机限流
* @param rate 速率(指定时间间隔产生的令牌数)
* @param rateInterval 速率间隔(时间间隔,单位:秒)
* @return true成功false失败
*/
public static boolean rateLimit(String key, RateType rateType, int rate, int rateInterval) {
RRateLimiter rateLimiter = CLIENT.getRateLimiter(key);
rateLimiter.trySetRate(rateType, rate, rateInterval, RateIntervalUnit.SECONDS);
return rateLimiter.tryAcquire(1);
}
/**
* 格式化键,将各子键用 : 拼接起来
*