import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;
1, the implementation class
@Slf4j
public class MucRpcThreadPoolExecutor {
/**
* 任务队列
* 设置有界队列长度为1024
*/
private static BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(1024);
private static ExecutorService executorService = new ThreadPoolExecutor(
4, 16, 60, TimeUnit.SECONDS,
queue,
new ThreadFactoryBuilder().setNameFormat("muc-rpc-thd-%d").build(),
new RpcExecutionHandler());
public static void asyncRpcSubmit(AbstractRpcRunner runner){
executorService.submit(runner);
}
private static class RpcExecutionHandler implements RejectedExecutionHandler{
@Override
public void rejectedExecution (R & lt the Runnable, the ThreadPoolExecutor Executor) {
String name = Thread.currentThread () getName ();.
IF (R & lt AbstractRpcRunner the instanceof) {
IF (! ((AbstractRpcRunner) R & lt) .getBaseRpcBo () = null)
name . = ((AbstractRpcRunner) R & lt) .getBaseRpcBo () getReqId ();
}
log.warn ( "RPC-MUC-thread-thread queue the pool is full, a new task is discarded: {}", name);
}
}
}
2 thread abstract class
// BaseRpcBo requesting entity class
public abstract class AbstractRpcRunner <T extends BaseRpcBo> implements Runnable {
protected T baseRpcBo;
public T getBaseRpcBo() {
return baseRpcBo;
}
public void setBaseRpcBo(T baseRpcBo) {
this.baseRpcBo = baseRpcBo;
}
}
3、实体类
@Data
public class BaseRpcBo the implements the Serializable {
/ **
* Request ID
* /
Private String reqId;
/ **
* remote call address
* /
@JSONField (= the serialize to false)
Private String rpcUrl;
/ **
* request header
* /
@JSONField (= the serialize to false)
Private the Map <String, String> headers;
}
. 4, calls the method
public void asyncGrowthUp(String uid) {
GrowthUpRpcBo rpcBo = new GrowthUpRpcBo();
rpcBo.setStamp(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
rpcBo.setUid(uid);
rpcBo.setReqId(UUIDUtil.randomId());
rpcBo.setRpcUrl(mjHttpUtils.getAbsUrl(MjConstant.API_GROWTH_UP_SYNC));
Map<String,String> header = new HashMap<>(1);
header.put("Content-Type", "application/json;charset=UTF-8");
rpcBo.setHeaders(header);
MucRpcThreadPoolExecutor.asyncRpcSubmit(new PostJsonRpcRunner(mjHttpUtils, rpcBo));
log.info("growth up notify to iot finish, uid:{}, reqId:{}", uid, rpcBo.getReqId());
}
5、GrowthUpRpcBo
@Data
public class GrowthUpRpcBo extends BaseRpcBo{
/**
* 请求时间戳
* 格式为 yyyyMMddHHmmss
*/
String stamp;
/**
* 用户id
*/
String uid;
}