
com.github.panhongan.utils.throttling.Throttling Maven / Gradle / Ivy
package com.github.panhongan.utils.throttling;
import java.util.function.Function;
import com.github.panhongan.utils.function.ThrowableFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.panhongan.utils.function.ThrowableFunction;
/**
* lalalu plus
*
*
* I : input
* O : output
* T : throwable
*/
public class Throttling {
private static final Logger logger = LoggerFactory.getLogger(Throttling.class);
public static O throttling(ThrottlingConfig throttlingConfig,
Function function,
I input,
O throttlingResult) {
try {
if (throttlingConfig.tryEnter()) {
return function.apply(input);
} else {
logger.warn("trigger throttling : {}", throttlingConfig.toString());
return throttlingResult;
}
} finally {
throttlingConfig.leave();
}
}
public static O throttling(ThrottlingConfig throttlingConfig,
ThrowableFunction function,
I input,
O throttlingResult) throws T {
try {
if (throttlingConfig.tryEnter()) {
return function.apply(input);
} else {
logger.warn("trigger throttling : {}", throttlingConfig.toString());
return throttlingResult;
}
} catch (Throwable t) {
logger.warn("", t);
throw t;
} finally {
throttlingConfig.leave();
}
}
}