redis_cell限流模块的使用-docker启动-java集成

本文介绍了如何在Java应用中利用Redis-cell模块进行限流控制。首先讲解了Redis-cell的基本概念和使用指令,如CL.THROTTLE,然后通过Docker部署Redis-cell,并展示了如何使用Jedis库自定义指令进行集成。最后提供了一个测试类`RedisCellTest`,演示了如何调用限流功能。参考《Redis的深度历险》了解更多。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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的深度历险》

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值