【问题标题】:How to set maximum number of permits for Redisson distributed lock如何设置 Redisson 分布式锁的最大许可数
【发布时间】:2017-02-24 01:34:13
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    所以我找到了解决方案。

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

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2020-06-19
      • 2014-05-11
      • 2020-11-25
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多