1

我有一个使用 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);
4

1 回答 1

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);
        }
于 2016-10-17T14:34:08.827 回答