0
点赞
收藏
分享

微信扫一扫

【分布式】Redis分布式之Semaphore

秀儿2020 2022-03-12 阅读 93
说明

使用方式同jdkt中的Semaphore,
配置文件参考:https://blog.csdn.net/qq_38428623/article/details/123217001?utm_source=app&app_version=5.1.1&code=app_1562916241&uLinkId=usr1mkqgl919blen

使用
package com.demo.redis.string;

import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * RedisSemaphore
 *
 * @author 王思勤
 */
public class RedisSemaphore {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 获取 字符串 的 RAtomicLong
     *
     * @param name 名称
     * @return 返回 值
     */
    public RSemaphore getSemaphore(String name) {
        RSemaphore semaphore = redissonClient.getSemaphore(name);
        Assert.notNull(semaphore, "semaphore is null");
        return semaphore;
    }

    /**
     * 获取 访问许可
     *
     * @param name 名称
     * @return 返回 访问许可
     */
    public boolean tryAcquire(String name) {
        return this.getSemaphore(name).tryAcquire();
    }

    /**
     * 获取 访问许可
     *
     * @param name    名称
     * @param permits 数量
     * @return 返回 访问许可
     */
    public boolean tryAcquire(String name, int permits) {
        return this.getSemaphore(name).tryAcquire(permits);
    }

    /**
     * 获取 访问许可
     *
     * @param name 名称
     * @throws InterruptedException interruptedException
     */
    public void acquire(String name) throws InterruptedException {
        this.getSemaphore(name).acquire();
    }

    /**
     * 获取 访问许可
     *
     * @param name    名称
     * @param permits 数量
     * @return 返回 访问许可
     * @throws InterruptedException interruptedException
     */
    public void acquire(String name, int permits) throws InterruptedException {
        this.getSemaphore(name).acquire(permits);
    }

    /**
     * await
     *
     * @param name 名称
     */
    public void release(String name) {
        this.getSemaphore(name).release();
    }

    /**
     * release
     *
     * @param name 名称
     * @param permits 数量
     */
    public void release(String name, int permits) {
        this.getSemaphore(name).release(permits);
    }
}
举报

相关推荐

0 条评论