如何设置Redisson分布式锁

时间:2016-10-14 14:56:13

标签: java semaphore amazon-elasticsearch distributed-lock redisson

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

该模块用于访问某个API并从中检索数据。问题是API使用漏桶算法,它将API调用限制为40,并且每隔0.5秒就可以调用API调用。 因此我得到Request limit exceeded例外。

为了解决这个问题,我决定实施分布式锁,并将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);

1 个答案:

答案 0 :(得分:0)

所以我找到了解决方案。

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);
        }
相关问题