com.github.cosycode.ext.hub.CurrentLimitClosureProxy Maven / Gradle / Ivy
Show all versions of extend-mod Show documentation
package com.github.cosycode.ext.hub;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.Semaphore;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
/**
* Description : 限流闭包代理类
*
* created in 2021/4/7
*
* @author CPF
**/
@Slf4j
public class CurrentLimitClosureProxy extends AbstractClosureProxy {
private final Semaphore semaphore;
public CurrentLimitClosureProxy(int limit, @NonNull T then) {
super(then);
check(limit);
semaphore = new Semaphore(limit);
}
public CurrentLimitClosureProxy(int limit, @NonNull T then, @NonNull BiFunction function) {
super(then, function);
check(limit);
semaphore = new Semaphore(limit);
}
public CurrentLimitClosureProxy(int limit, @NonNull T then, @NonNull BiConsumer biConsumer) {
super(then, biConsumer);
check(limit);
semaphore = new Semaphore(limit);
}
private void check(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit cannot less than 1");
}
}
@Override
public R closureFunction(P params) {
try {
semaphore.acquire();
biFunction.apply(functional, params);
} catch (InterruptedException e) {
log.error("Failed to get signal, params: " + params, e);
Thread.currentThread().interrupt();
} finally {
semaphore.release();
}
return null;
}
}