有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何设置Redisson分布式锁的最大许可数

我有一个Java模块,用AWS Lambda运行。这意味着该模块的多个实例可以同时运行

该模块用于访问特定的API并从中检索数据。问题在于,API使用了一种漏桶算法,该算法将API调用限制为40次,并且每0.5秒提供一次API调用。 正因为如此,我得到了一个Request limit exceeded异常

为了解决这个问题,我决定实现一个分布式锁,并在AWS ElastiCache(分布式Redis集群)中使用redisson。在检查了redisson的文档之后,我得出结论,我应该使用PermitExpirableSemaphore来创建一个带有租约的锁(在我的例子中是500毫秒)

问题是,我找不到办法将可用许可限制在40个

你知道怎么做吗

下面是我的代码示例:

    Config config = new Config();
    config.useElasticacheServers()
                .setScanInterval(2000) // cluster state scan interval in milliseconds
                .addNodeAddress("my.cache.amazonaws.com:6379");

    RedissonClient redissonClient = Redisson.create(config);
    RPermitExpirableSemaphore semaphore = redissonClient.getPermitExpirableSemaphore("mySemaphore");

    String permitId = semaphore.acquire(500, TimeUnit.MILLISECONDS);

    // Make the API call

    semaphore.release(permitId);

共 (1) 个答案

  1. # 1 楼答案

    所以我找到了解决办法

    Redisson中有一个addPermits方法,可以用来增加许可证的数量。一个信号量只能使用一次

            // If there are no permits set this will throw a NullPointerException.
            // This means that the permits should be added. If the addPermits is executed more than once,
            // each consecutive call will add the permits to the existing ones. eg: 35, 70, etc.
            try
            {
                int permits = _semaphore.availablePermits();
    
            }
            catch (NullPointerException ex)
            {
                _semaphore.addPermits(35);
            }