redis限流java写法
时间: 2023-05-12 18:07:02 浏览: 120
可以使用 Redis 的令牌桶算法来实现限流,具体的 Java 代码实现可以参考以下示例:
```java
public class RedisRateLimiter {
private final Jedis jedis;
private final String key;
private final int limit;
private final long interval;
public RedisRateLimiter(Jedis jedis, String key, int limit, long interval) {
this.jedis = jedis;
this.key = key;
this.limit = limit;
this.interval = interval;
}
public boolean acquire() {
long now = System.currentTimeMillis();
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.zadd(key, now, String.valueOf(now));
pipeline.zremrangeByScore(key, 0, now - interval);
pipeline.zcard(key);
pipeline.expire(key, (int) (interval / 1000));
List<Object> results = pipeline.exec();
long count = (Long) results.get(results.size() - 2);
return count <= limit;
}
}
```
使用时,可以先创建一个 RedisRateLimiter 对象,然后在需要进行限流的地方调用 acquire() 方法,如果返回 true,表示可以继续执行业务逻辑,否则需要等待一段时间后再尝试。例如:
```java
Jedis jedis = new Jedis("localhost");
RedisRateLimiter limiter = new RedisRateLimiter(jedis, "my-limiter", 10, 1000);
while (true) {
if (limiter.acquire()) {
// 执行业务逻辑
} else {
Thread.sleep(100);
}
}
```
阅读全文