我有一个 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/