Redis-cell限流模块在java中的基本使用
基本介绍
Redis-cell模块是Redis4.0提供的一个限流模块,该模块使用了漏斗算法,提供了原子的限流指令,唯一的一条指令就是
cl.throttle 唯一的指令
cl.throttle zedomi:reply 15 30 60 1
漏斗容量15,每60s最多30次(漏水速率)
返回值:0 运行 1 拒绝
15 漏斗容量capacity
14 漏斗剩余空间 left_quota
-1 被拒绝了,多长时间后重试()
2 多长时间后,漏斗完全空出来(单位秒)
Docker安装
docker pull hsz1273327/redis-cell //拉取镜像
docker run -d -p 6380:6379 hsz1273327/redis-cell //映射至6380端口
redis-cli -p 6380 //启动客户端
JAVA集成
引入Maven包
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.5.0</version>
</dependency>
编写指令
//因为是扩展的指令,所以需要自己定义指令
import redis.clients.jedis.commands.ProtocolCommand;
import redis.clients.jedis.util.SafeEncoder;
public enum CellCommand implements ProtocolCommand {
CLTHROTTLE("CL.THROTTLE");
private final byte[] raw;
CellCommand(String alt) {
raw = SafeEncoder.encode(alt);
}
@Override
public byte[] getRaw() {
return raw;
}
}
import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import java.util.List;
/**
* 测试类
*/
public class RedisCellTest {
private Jedis jedis;
public RedisCellTest(Jedis jedis) {
this.jedis = jedis;
}
public boolean isActionAllow(String key, String capacity, String number, String time) {
Client client = jedis.getClient();
boolean is;
client.sendCommand(CellCommand.CLTHROTTLE, key, capacity, number, time);
List<Long> replay = client.getIntegerMultiBulkReply();
if (replay.get(2) > 0) {
is = true;
} else {
is = false;
}
System.out.println(replay);
client.close();
return is;
}
public static void main(String[] args) {
RedisCellTest redisCellTest = new RedisCellTest(new Jedis("192.168.31.149", 6381));
for (int i = 0; i < 20; i++) {
System.out.println(redisCellTest.isActionAllow("zedomi:reply", "14", "30", "60"));
}
}
}
基本的redis-cell测试使用,希望对大家有帮助
参考文献:《Redis的深度历险》
————————————————
版权声明:本文为CSDN博主「zedomi」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zedomi/article/details/113410248