package com.ruoyi.common.utils.redis;

import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 信号量 工具类
 */
@Component
public class SemaphoreTool {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 获取信号量对象
     * @param key
     * @return
     */
    public RSemaphore getRSemaphore(String key){
        return redissonClient.getSemaphore(key);
    }

    /**
     * 设置信号量的值
     * @param key
     * @param size
     * @return
     */
    public Boolean setRSemaphorePermits(String key,Integer size) {
        RSemaphore semaphore = this.getRSemaphore(key);
        return semaphore.trySetPermits(size);
    }


    /**
     * 尝试获得信号量
     */
    public boolean tryAcquire(String key, int size) {
        RSemaphore semaphore = this.getRSemaphore(key);
        return semaphore.tryAcquire(size);
    }

    /**
     * 释放信号量
     */
    public void release(String key, int size) {
        RSemaphore semaphore = this.getRSemaphore(key);
        semaphore.release(size);
    }

    /**
     * 信号量的permits数
     * 获取当前信号量的剩余数量
     */
    public Integer permitsNum(String key) {
        RSemaphore semaphore = this.getRSemaphore(key);
        return semaphore.availablePermits();
    }

    /**
     * 清空permits
     *
     */
    public Integer drainPermits(String key) {
        RSemaphore semaphore = this.getRSemaphore(key);
        return semaphore.drainPermits();
    }

}
