Java 如何设置Redisson分布式锁的最大许可数
我有一个Java模块,它使用AWS Lambda运行。这意味着模块的多个实例可以同时运行 该模块用于访问某个API并从中检索数据。问题在于API使用了一个漏桶算法,该算法将API调用限制为40次,并且每0.5秒提供一次API调用。 因此,我得到了一个超出请求限制的Java 如何设置Redisson分布式锁的最大许可数,java,semaphore,amazon-elasticsearch,distributed-lock,redisson,Java,Semaphore,amazon Elasticsearch,Distributed Lock,Redisson,我有一个Java模块,它使用AWS Lambda运行。这意味着模块的多个实例可以同时运行 该模块用于访问某个API并从中检索数据。问题在于API使用了一个漏桶算法,该算法将API调用限制为40次,并且每0.5秒提供一次API调用。 因此,我得到了一个超出请求限制的异常 为了解决这个问题,我决定实现一个分布式锁,并与AWS ElastiCache(分布式Redis集群)一起使用。在检查了redisson的文档之后,我得出结论,我应该使用PermitExpirableSemaphore,它可以创建一
异常
为了解决这个问题,我决定实现一个分布式锁,并与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中有一个addPermissions
方法,可用于添加许可数量。对于一个信号量,它应该只使用一次
// 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);
}
所以我找到了解决办法
Redisson中有一个addPermissions
方法,可用于添加许可数量。对于一个信号量,它应该只使用一次
// 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);
}