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

标签 java semaphore amazon-elasticsearch distributed-lock redisson

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

该模块用于访问某个API并从中检索数据。问题在于该 API 使用漏桶算法,该算法将 API 调用限制为 40 次,并且每 0.5 秒进行一次 API 调用。 因此,我收到超出请求限制异常。

为了解决这个问题,我决定实现分布式锁并使用 redisson与AWS ElastiCache(分布式Redis集群)。在检查了 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);

最佳答案

所以我找到了解决方案。

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);
        }

关于java - 如何设置Redisson分布式锁的最大许可数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046205/

相关文章:

elasticsearch - 如何在 Elasticsearch (aws)中存储日期范围数据并搜索范围?

amazon-web-services - 使用 logstash 将数据流式传输到 amazon elasticsearch?

elasticsearch - Logstash:是否有一种方法可以在迁移时更改文档中的某些属性

java - 如何在属性中将字体安装到 NetBeans?

c - 为什么这个信号量代码失败?

std::strings 队列通过 JNI 需要 C++ 共享内存吗?

与 Ubuntu 中的 CPP 应用程序兼容的 PHP 信号量

java - coverage.ec 文件格式

java - 我有一种从 String[] 中删除空值的方法,我如何为该函数创建一个方法并稍后调用它? java

java - 使用 JSP 进行对象请求