序言
JDK1.8以内的掌控系统,应付想固定式的掌控几段标识符的“mammalian用户数量”的情景。如前所述Semaphore与此同时实现Advance“开闭”。特别注意:无法全然代替“穆萨sentinel”模块,增设的“车辆通行量或是叫作讯号量”,有别于其本质上的“QPS共振频率”。前述上用作管制几段标识符与此同时被运转的量,绝非按秒计。
产品目录
SemaphoreUtil.java 核心理念辅助工具类SemaphoreType.java 讯号类型隐式Work.java lambdaUSB
上码
SemaphoreUtil.java@Slf4j
public class SemaphoreUtil{
//思路商业模式,科枫储存数个的semaphore
//即使他们前述销售业务中不可能将多于两个地方性须要开闭,或是想管制相同的“车辆通行量”。因此透过建立和采用数个semaphore示例来满足用户
static Map<SemaphoreType, Semaphore> semaphores = new ConcurrentHashMap<>();
static Map<SemaphoreType, Integer> semaphoreConfig = new HashMap<>();
private static final int unit_num = 2;//签订合同了每天透过须要耗用三个讯号
static {
//增设各式各样讯号阀的最小电导率。虽然签订合同了每天透过须要耗用三个讯号,因此提议这儿是单数semaphoreConfig.put(SemaphoreType.TABLEDATA,2);
}
/**
* @desc@author
*/
public static synchronized Semaphore getSemaphore(SemaphoreType semaphoreType){
//讯号阀不存在才建立新的
if(semaphores.get(semaphoreType) ==null){
log.info(“建立新的Semaphore:{}”, semaphoreType.getDes());
Semaphore excelexportSemaphore =newSemaphore(semaphoreConfig.get(semaphoreType));
semaphores.put(semaphoreType, excelexportSemaphore);
}return semaphores.get(semaphoreType);
}
public static <T> T execute(SemaphoreType semaphoreType, Work<T> work){
Preconditions.checkArgument(semaphoreType!=null, “semaphoreType is null”);
//标识是否须要释放
boolean flag = false;
try {
if(getSemaphore(semaphoreType).tryAcquire(unit_num)){
flag =true;
return work.run();
}else{
System.out.println(semaphoreType.getDes().concat(“超限”) + getSemaphore(semaphoreType).availablePermits());
return null;
}
}catch(Exception e){
e.printStackTrace();return null;
}finally {
if(flag){
getSemaphore(semaphoreType).release(unit_num);
}
}
}//体验
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
final intf_i = i;
GlobalThreadPool.execute(() -> {
String ret = SemaphoreUtil.execute(SemaphoreType.TABLEDATA, () -> {try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(“” + f_i);
return “”;
});
});
}
GlobalThreadPool.shutdown(false);
}
}SemaphoreType.java//定义用到开闭的销售业务情景的隐式
@Getter
public enumSemaphoreType {
TABLEDATA(“掌控台列表数据查询”);
private String des;
SemaphoreType(String des){
this.des = des;
}
}Work.javapublic interface Work<T> {
T run();
}拓展
标识符不多,拓展和改造都比较简单。比如想拓展成注解可用,可以见下文:SemaphoreAnno.java 自定义注解@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interfaceSemaphoreAnno {SemaphoreType type();
}SemaphoreAspect.java 切面@Aspect
@Slf4j
@Component
@Order(1)
@Configuration
public class SemaphoreAspect {
@Around(“@annotation(semaphoreAnno)”)
publicObject around(ProceedingJoinPoint point, SemaphoreAnno semaphoreAnno) {
Object ret;
ret = SemaphoreUtil.execute(semaphoreAnno.type(), () -> {try {
return point.proceed();
} catch(Throwable throwable) {
throwable.printStackTrace();return null;
}
});
return ret;
}
}采用方式@SemaphoreAnno(type = SemaphoreType.TABLEDATA)