Optimize code format and delete meaningless blank lines

pull/218/head
chen.ma 2 years ago
parent 9f8331c19b
commit 7cb555804e

@ -53,7 +53,5 @@ public interface ClientCloseHookExecute {
* groupKey * groupKey
*/ */
private String groupKey; private String groupKey;
} }
} }

@ -54,5 +54,4 @@ public interface JsonFacade {
* @return * @return
*/ */
<T> List<T> parseArray(String text, Class<T> clazz); <T> List<T> parseArray(String text, Class<T> clazz);
} }

@ -36,5 +36,4 @@ public interface NotifyConfigBuilder {
* @return * @return
*/ */
Map<String, List<NotifyConfigDTO>> buildNotify(); Map<String, List<NotifyConfigDTO>> buildNotify();
} }

@ -45,5 +45,4 @@ public interface ThreadDetailState {
* @return * @return
*/ */
List<ThreadDetailStateInfo> getThreadDetailStateInfo(ThreadPoolExecutor threadPoolExecutor); List<ThreadDetailStateInfo> getThreadDetailStateInfo(ThreadPoolExecutor threadPoolExecutor);
} }

@ -18,7 +18,7 @@
package cn.hippo4j.common.api; package cn.hippo4j.common.api;
/** /**
* Thread pool dynamic refresh. * Thread-pool dynamic refresh.
* *
* @author chen.ma * @author chen.ma
* @date 2022/2/26 12:26 * @date 2022/2/26 12:26
@ -31,5 +31,4 @@ public interface ThreadPoolDynamicRefresh {
* @param content * @param content
*/ */
void dynamicRefresh(String content); void dynamicRefresh(String content);
} }

@ -93,5 +93,4 @@ public class ApplicationContextHolder implements ApplicationContextAware {
public static ApplicationContext getInstance() { public static ApplicationContext getInstance() {
return CONTEXT; return CONTEXT;
} }
} }

@ -102,5 +102,4 @@ public class Constants {
public static final String EXECUTE_TIMEOUT_TRACE = "executeTimeoutTrace"; public static final String EXECUTE_TIMEOUT_TRACE = "executeTimeoutTrace";
public static final int HTTP_EXECUTE_TIMEOUT = 5000; public static final int HTTP_EXECUTE_TIMEOUT = 5000;
} }

@ -27,11 +27,5 @@ import java.io.Serializable;
*/ */
public interface Builder<T> extends Serializable { public interface Builder<T> extends Serializable {
/**
* Build.
*
* @return
*/
T build(); T build();
} }

@ -145,7 +145,5 @@ public class AbstractSubjectCenter {
* Clear config cache. * Clear config cache.
*/ */
CLEAR_CONFIG_CACHE CLEAR_CONFIG_CACHE
} }
} }

@ -31,5 +31,4 @@ public interface Observer<T> {
* @param observerMessage * @param observerMessage
*/ */
void accept(ObserverMessage<T> observerMessage); void accept(ObserverMessage<T> observerMessage);
} }

@ -25,11 +25,5 @@ package cn.hippo4j.common.design.observer;
*/ */
public interface ObserverMessage<T> { public interface ObserverMessage<T> {
/**
* Message.
*
* @return
*/
T message(); T message();
} }

@ -53,5 +53,4 @@ public enum DelEnum {
public String toString() { public String toString() {
return statusCode; return statusCode;
} }
} }

@ -59,5 +59,4 @@ public enum EnableEnum {
public static boolean getBool(Integer intStatusCode) { public static boolean getBool(Integer intStatusCode) {
return Objects.equals(intStatusCode, EnableEnum.YES.getIntCode()) ? true : false; return Objects.equals(intStatusCode, EnableEnum.YES.getIntCode()) ? true : false;
} }
} }

@ -41,5 +41,4 @@ public class ExecutorFactory {
return executorService; return executorService;
} }
} }
} }

@ -59,7 +59,6 @@ public class ThreadPoolManager {
lockers.put(tenantId, new Object()); lockers.put(tenantId, new Object());
} }
} }
final Object monitor = lockers.get(tenantId); final Object monitor = lockers.get(tenantId);
synchronized (monitor) { synchronized (monitor) {
Map<String, Set<ExecutorService>> map = resourcesManager.get(tenantId); Map<String, Set<ExecutorService>> map = resourcesManager.get(tenantId);
@ -76,5 +75,4 @@ public class ThreadPoolManager {
map.get(group).add(executor); map.get(group).add(executor);
} }
} }
} }

@ -26,12 +26,5 @@ package cn.hippo4j.common.function;
@FunctionalInterface @FunctionalInterface
public interface Matcher<T> { public interface Matcher<T> {
/**
* Match.
*
* @param t
* @return
*/
boolean match(T t); boolean match(T t);
} }

@ -26,9 +26,5 @@ package cn.hippo4j.common.function;
@FunctionalInterface @FunctionalInterface
public interface NoArgsConsumer { public interface NoArgsConsumer {
/**
*
*/
void accept(); void accept();
} }

@ -98,5 +98,4 @@ public class GlobalRemotePoolInfo implements Serializable {
* content * content
*/ */
private String content; private String content;
} }

@ -184,7 +184,5 @@ public class InstanceInfo {
private String lastDirtyTimestamp; private String lastDirtyTimestamp;
private String status; private String status;
} }
} }

@ -42,5 +42,4 @@ public class ManyPoolRunStateInfo extends PoolRunStateInfo {
* state * state
*/ */
private String state; private String state;
} }

@ -59,5 +59,4 @@ public class PoolBaseInfo {
* keepAliveTime * keepAliveTime
*/ */
private Long keepAliveTime; private Long keepAliveTime;
} }

@ -115,5 +115,4 @@ public interface PoolParameter {
* @return * @return
*/ */
Integer getAllowCoreThreadTimeOut(); Integer getAllowCoreThreadTimeOut();
} }

@ -103,5 +103,4 @@ public class PoolParameterInfo implements PoolParameter, Serializable {
* allowCoreThreadTimeOut * allowCoreThreadTimeOut
*/ */
private Integer allowCoreThreadTimeOut; private Integer allowCoreThreadTimeOut;
} }

@ -119,5 +119,4 @@ public class PoolRunStateInfo extends PoolBaseInfo implements Serializable {
public Integer getSimplePeakLoad() { public Integer getSimplePeakLoad() {
return Integer.parseInt(getPeakLoad().replace("%", "")); return Integer.parseInt(getPeakLoad().replace("%", ""));
} }
} }

@ -51,5 +51,4 @@ public class ThreadDetailStateInfo {
* threadStack * threadStack
*/ */
private List<String> threadStack; private List<String> threadStack;
} }

@ -41,5 +41,4 @@ public class TokenInfo {
* tokenTtl * tokenTtl
*/ */
private Long tokenTtl; private Long tokenTtl;
} }

@ -46,5 +46,4 @@ public abstract class AbstractMessage<T extends Message> implements Message {
* message * message
*/ */
private List<T> messages; private List<T> messages;
} }

@ -48,5 +48,4 @@ public interface Message<T extends Message> extends Serializable {
* @return * @return
*/ */
List<T> getMessages(); List<T> getMessages();
} }

@ -48,5 +48,4 @@ public interface MessageRequest<T extends Message> {
* @return * @return
*/ */
MessageTypeEnum getMessageType(); MessageTypeEnum getMessageType();
} }

@ -34,5 +34,4 @@ public enum MessageTypeEnum {
* DEFAULT * DEFAULT
*/ */
DEFAULT DEFAULT
} }

@ -64,5 +64,4 @@ public class MessageWrapper implements MessageRequest<Message> {
public MessageTypeEnum getMessageType() { public MessageTypeEnum getMessageType() {
return messageType; return messageType;
} }
} }

@ -84,5 +84,4 @@ public class RuntimeMessage extends AbstractMessage {
* timestamp * timestamp
*/ */
private Long timestamp; private Long timestamp;
} }

@ -54,5 +54,4 @@ public class AlarmControlDTO {
public String buildPk() { public String buildPk() {
return StrUtil.builder(threadPool, "+", platform).toString(); return StrUtil.builder(threadPool, "+", platform).toString();
} }
} }

@ -52,7 +52,6 @@ public class AlarmControlHandler {
if (cache == null) { if (cache == null) {
return false; return false;
} }
String pkId = cache.getIfPresent(alarmControl.getTypeEnum().name()); String pkId = cache.getIfPresent(alarmControl.getTypeEnum().name());
if (StrUtil.isBlank(pkId)) { if (StrUtil.isBlank(pkId)) {
ReentrantLock lock = threadPoolLock.get(threadPoolKey); ReentrantLock lock = threadPoolLock.get(threadPoolKey);
@ -68,7 +67,6 @@ public class AlarmControlHandler {
lock.unlock(); lock.unlock();
} }
} }
return false; return false;
} }
@ -85,10 +83,8 @@ public class AlarmControlHandler {
.expireAfterWrite(interval, TimeUnit.MINUTES) .expireAfterWrite(interval, TimeUnit.MINUTES)
.build(); .build();
threadPoolAlarmCache.put(threadPoolKey, cache); threadPoolAlarmCache.put(threadPoolKey, cache);
// Set the lock to prevent false sending of alarm information. // Set the lock to prevent false sending of alarm information.
ReentrantLock reentrantLock = new ReentrantLock(); ReentrantLock reentrantLock = new ReentrantLock();
threadPoolLock.put(threadPoolKey, reentrantLock); threadPoolLock.put(threadPoolKey, reentrantLock);
} }
} }

@ -57,7 +57,6 @@ public class HippoBaseSendMessageService implements HippoSendMessageService, Com
if (CollUtil.isEmpty(notifyList)) { if (CollUtil.isEmpty(notifyList)) {
return; return;
} }
notifyList.forEach(each -> { notifyList.forEach(each -> {
try { try {
SendMessageHandler messageHandler = sendMessageHandlers.get(each.getPlatform()); SendMessageHandler messageHandler = sendMessageHandlers.get(each.getPlatform());
@ -65,7 +64,6 @@ public class HippoBaseSendMessageService implements HippoSendMessageService, Com
log.warn("Please configure alarm notification on the server. key :: [{}]", threadPoolId); log.warn("Please configure alarm notification on the server. key :: [{}]", threadPoolId);
return; return;
} }
if (isSendAlarm(each.getTpId(), each.getPlatform(), typeEnum)) { if (isSendAlarm(each.getTpId(), each.getPlatform(), typeEnum)) {
alarmNotifyRequest.setNotifyTypeEnum(typeEnum); alarmNotifyRequest.setNotifyTypeEnum(typeEnum);
messageHandler.sendAlarmMessage(each, alarmNotifyRequest); messageHandler.sendAlarmMessage(each, alarmNotifyRequest);
@ -85,7 +83,6 @@ public class HippoBaseSendMessageService implements HippoSendMessageService, Com
log.warn("Please configure alarm notification on the server. key :: [{}]", threadPoolId); log.warn("Please configure alarm notification on the server. key :: [{}]", threadPoolId);
return; return;
} }
notifyList.forEach(each -> { notifyList.forEach(each -> {
try { try {
SendMessageHandler messageHandler = sendMessageHandlers.get(each.getPlatform()); SendMessageHandler messageHandler = sendMessageHandlers.get(each.getPlatform());
@ -93,7 +90,6 @@ public class HippoBaseSendMessageService implements HippoSendMessageService, Com
log.warn("Please configure alarm notification on the server. key :: [{}]", threadPoolId); log.warn("Please configure alarm notification on the server. key :: [{}]", threadPoolId);
return; return;
} }
messageHandler.sendChangeMessage(each, changeParameterNotifyRequest); messageHandler.sendChangeMessage(each, changeParameterNotifyRequest);
} catch (Exception ex) { } catch (Exception ex) {
log.warn("Failed to send thread pool change notification. key :: [{}]", threadPoolId, ex); log.warn("Failed to send thread pool change notification. key :: [{}]", threadPoolId, ex);
@ -115,7 +111,6 @@ public class HippoBaseSendMessageService implements HippoSendMessageService, Com
.platform(platform) .platform(platform)
.typeEnum(typeEnum) .typeEnum(typeEnum)
.build(); .build();
return alarmControlHandler.isSendAlarm(alarmControl); return alarmControlHandler.isSendAlarm(alarmControl);
} }
@ -124,7 +119,6 @@ public class HippoBaseSendMessageService implements HippoSendMessageService, Com
Map<String, SendMessageHandler> sendMessageHandlerMap = Map<String, SendMessageHandler> sendMessageHandlerMap =
ApplicationContextHolder.getBeansOfType(SendMessageHandler.class); ApplicationContextHolder.getBeansOfType(SendMessageHandler.class);
sendMessageHandlerMap.values().forEach(each -> sendMessageHandlers.put(each.getType(), each)); sendMessageHandlerMap.values().forEach(each -> sendMessageHandlers.put(each.getType(), each));
Map<String, List<NotifyConfigDTO>> buildNotify = notifyConfigBuilder.buildNotify(); Map<String, List<NotifyConfigDTO>> buildNotify = notifyConfigBuilder.buildNotify();
notifyConfigs.putAll(buildNotify); notifyConfigs.putAll(buildNotify);
} }
@ -137,5 +131,4 @@ public class HippoBaseSendMessageService implements HippoSendMessageService, Com
public synchronized void putPlatform(Map<String, List<NotifyConfigDTO>> notifyConfigs) { public synchronized void putPlatform(Map<String, List<NotifyConfigDTO>> notifyConfigs) {
this.notifyConfigs.putAll(notifyConfigs); this.notifyConfigs.putAll(notifyConfigs);
} }
} }

@ -42,5 +42,4 @@ public interface HippoSendMessageService {
* @param changeParameterNotifyRequest * @param changeParameterNotifyRequest
*/ */
void sendChangeMessage(ChangeParameterNotifyRequest changeParameterNotifyRequest); void sendChangeMessage(ChangeParameterNotifyRequest changeParameterNotifyRequest);
} }

@ -79,5 +79,4 @@ public class NotifyConfigDTO {
* *
*/ */
private NotifyTypeEnum typeEnum; private NotifyTypeEnum typeEnum;
} }

@ -39,5 +39,4 @@ public enum NotifyPlatformEnum {
* WECHAT * WECHAT
*/ */
WECHAT WECHAT
} }

@ -49,5 +49,4 @@ public enum NotifyTypeEnum {
* TIMEOUT * TIMEOUT
*/ */
TIMEOUT TIMEOUT
} }

@ -49,5 +49,4 @@ public interface SendMessageHandler<T extends NotifyRequest, R extends NotifyReq
* @param changeParameterNotifyRequest * @param changeParameterNotifyRequest
*/ */
void sendChangeMessage(NotifyConfigDTO notifyConfig, R changeParameterNotifyRequest); void sendChangeMessage(NotifyConfigDTO notifyConfig, R changeParameterNotifyRequest);
} }

@ -69,5 +69,4 @@ public class ThreadPoolNotifyAlarm {
*/ */
@Deprecated @Deprecated
private Map<String, String> receives; private Map<String, String> receives;
} }

@ -39,5 +39,4 @@ public class ThreadPoolNotifyDTO {
* notifyList * notifyList
*/ */
private List<NotifyConfigDTO> notifyList; private List<NotifyConfigDTO> notifyList;
} }

@ -110,5 +110,4 @@ public class DingAlarmConstants {
"<font color=#708090 size=2>OWNER@%s</font> \n\n" + "<font color=#708090 size=2>OWNER@%s</font> \n\n" +
" --- \n\n " + " --- \n\n " +
"**播报时间:%s**"; "**播报时间:%s**";
} }

@ -62,7 +62,6 @@ public class DingSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
public void sendAlarmMessage(NotifyConfigDTO notifyConfig, AlarmNotifyRequest alarmNotifyRequest) { public void sendAlarmMessage(NotifyConfigDTO notifyConfig, AlarmNotifyRequest alarmNotifyRequest) {
String[] receives = notifyConfig.getReceives().split(","); String[] receives = notifyConfig.getReceives().split(",");
String afterReceives = Joiner.on(", @").join(receives); String afterReceives = Joiner.on(", @").join(receives);
String dingAlarmTxt; String dingAlarmTxt;
String dingAlarmTimoutReplaceTxt; String dingAlarmTimoutReplaceTxt;
if (Objects.equals(alarmNotifyRequest.getNotifyTypeEnum(), NotifyTypeEnum.TIMEOUT)) { if (Objects.equals(alarmNotifyRequest.getNotifyTypeEnum(), NotifyTypeEnum.TIMEOUT)) {
@ -73,7 +72,6 @@ public class DingSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
} else { } else {
dingAlarmTimoutReplaceTxt = StrUtil.replace(DING_ALARM_TIMOUT_REPLACE_TXT, DING_ALARM_TIMOUT_TRACE_REPLACE_TXT, ""); dingAlarmTimoutReplaceTxt = StrUtil.replace(DING_ALARM_TIMOUT_REPLACE_TXT, DING_ALARM_TIMOUT_TRACE_REPLACE_TXT, "");
} }
dingAlarmTimoutReplaceTxt = String.format(dingAlarmTimoutReplaceTxt, alarmNotifyRequest.getExecuteTime(), alarmNotifyRequest.getExecuteTimeOut()); dingAlarmTimoutReplaceTxt = String.format(dingAlarmTimoutReplaceTxt, alarmNotifyRequest.getExecuteTime(), alarmNotifyRequest.getExecuteTimeOut());
dingAlarmTxt = StrUtil.replace(DING_ALARM_TXT, DING_ALARM_TIMOUT_REPLACE_TXT, dingAlarmTimoutReplaceTxt); dingAlarmTxt = StrUtil.replace(DING_ALARM_TXT, DING_ALARM_TIMOUT_REPLACE_TXT, dingAlarmTimoutReplaceTxt);
} else { } else {
@ -125,20 +123,14 @@ public class DingSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
notifyConfig.getInterval(), notifyConfig.getInterval(),
// 当前时间 // 当前时间
DateUtil.now()); DateUtil.now());
execute(notifyConfig, DingAlarmConstants.DING_ALARM_TITLE, text, Lists.newArrayList(receives)); execute(notifyConfig, DingAlarmConstants.DING_ALARM_TITLE, text, Lists.newArrayList(receives));
} }
@Override @Override
public void sendChangeMessage(NotifyConfigDTO notifyConfig, ChangeParameterNotifyRequest changeParameterNotifyRequest) { public void sendChangeMessage(NotifyConfigDTO notifyConfig, ChangeParameterNotifyRequest changeParameterNotifyRequest) {
String threadPoolId = changeParameterNotifyRequest.getThreadPoolId(); String threadPoolId = changeParameterNotifyRequest.getThreadPoolId();
String[] receives = notifyConfig.getReceives().split(","); String[] receives = notifyConfig.getReceives().split(",");
String afterReceives = Joiner.on(", @").join(receives); String afterReceives = Joiner.on(", @").join(receives);
/**
* hesitant e.g.
*/
String text = String.format( String text = String.format(
DING_NOTICE_TXT, DING_NOTICE_TXT,
// 环境 // 环境
@ -206,5 +198,4 @@ public class DingSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
log.error("Ding failed to send message", ex); log.error("Ding failed to send message", ex);
} }
} }
} }

@ -73,5 +73,4 @@ public class LarkAlarmConstants {
*/ */
public static final String LARK_NOTICE_JSON_STR = public static final String LARK_NOTICE_JSON_STR =
"{\"msg_type\":\"interactive\",\"card\":{\"config\":{\"wide_screen_mode\":true},\"header\":{\"template\":\"greed\",\"title\":{\"content\":\"[通知] %s 动态线程池参数变更\",\"tag\":\"plain_text\"}},\"elements\":[{\"fields\":[{\"is_short\":true,\"text\":{\"content\":\"** 线程池ID** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 应用名称:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 应用实例:** %s\",\"tag\":\"lark_md\"}}],\"tag\":\"div\"},{\"tag\":\"hr\"},{\"fields\":[{\"is_short\":true,\"text\":{\"content\":\"** 核心线程数:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 最大线程数:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 核心线程超时:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 线程存活时间:** %s\",\"tag\":\"lark_md\"}}],\"tag\":\"div\"},{\"tag\":\"hr\"},{\"fields\":[{\"is_short\":true,\"text\":{\"content\":\"** 队列类型:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 队列容量:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 执行超时时间:** %s\",\"tag\":\"lark_md\"}}],\"tag\":\"div\"},{\"tag\":\"hr\"},{\"fields\":[{\"is_short\":true,\"text\":{\"content\":\"** AGO 拒绝策略:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** NOW 拒绝策略:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** OWNER** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 播报时间: ** %s\",\"tag\":\"lark_md\"}}],\"tag\":\"div\"},{\"tag\":\"hr\"},{\"tag\":\"note\",\"elements\":[{\"tag\":\"plain_text\",\"content\":\"提示:动态线程池配置变更实时通知(无限制)\"}]}]}}"; "{\"msg_type\":\"interactive\",\"card\":{\"config\":{\"wide_screen_mode\":true},\"header\":{\"template\":\"greed\",\"title\":{\"content\":\"[通知] %s 动态线程池参数变更\",\"tag\":\"plain_text\"}},\"elements\":[{\"fields\":[{\"is_short\":true,\"text\":{\"content\":\"** 线程池ID** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 应用名称:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 应用实例:** %s\",\"tag\":\"lark_md\"}}],\"tag\":\"div\"},{\"tag\":\"hr\"},{\"fields\":[{\"is_short\":true,\"text\":{\"content\":\"** 核心线程数:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 最大线程数:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 核心线程超时:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 线程存活时间:** %s\",\"tag\":\"lark_md\"}}],\"tag\":\"div\"},{\"tag\":\"hr\"},{\"fields\":[{\"is_short\":true,\"text\":{\"content\":\"** 队列类型:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 队列容量:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 执行超时时间:** %s\",\"tag\":\"lark_md\"}}],\"tag\":\"div\"},{\"tag\":\"hr\"},{\"fields\":[{\"is_short\":true,\"text\":{\"content\":\"** AGO 拒绝策略:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** NOW 拒绝策略:** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** OWNER** %s\",\"tag\":\"lark_md\"}},{\"is_short\":true,\"text\":{\"content\":\"** 播报时间: ** %s\",\"tag\":\"lark_md\"}}],\"tag\":\"div\"},{\"tag\":\"hr\"},{\"tag\":\"note\",\"elements\":[{\"tag\":\"plain_text\",\"content\":\"提示:动态线程池配置变更实时通知(无限制)\"}]}]}}";
} }

@ -56,7 +56,6 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
@SneakyThrows @SneakyThrows
public void sendAlarmMessage(NotifyConfigDTO notifyConfig, AlarmNotifyRequest alarmNotifyRequest) { public void sendAlarmMessage(NotifyConfigDTO notifyConfig, AlarmNotifyRequest alarmNotifyRequest) {
String afterReceives = getReceives(notifyConfig.getReceives()); String afterReceives = getReceives(notifyConfig.getReceives());
String larkAlarmTxt; String larkAlarmTxt;
String larkAlarmTimoutReplaceTxt; String larkAlarmTimoutReplaceTxt;
if (Objects.equals(alarmNotifyRequest.getNotifyTypeEnum(), NotifyTypeEnum.TIMEOUT)) { if (Objects.equals(alarmNotifyRequest.getNotifyTypeEnum(), NotifyTypeEnum.TIMEOUT)) {
@ -67,7 +66,6 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
} else { } else {
larkAlarmTimoutReplaceTxt = StrUtil.replace(LARK_ALARM_TIMOUT_REPLACE_TXT, LARK_ALARM_TIMOUT_TRACE_REPLACE_TXT, ""); larkAlarmTimoutReplaceTxt = StrUtil.replace(LARK_ALARM_TIMOUT_REPLACE_TXT, LARK_ALARM_TIMOUT_TRACE_REPLACE_TXT, "");
} }
larkAlarmTimoutReplaceTxt = String.format(larkAlarmTimoutReplaceTxt, alarmNotifyRequest.getExecuteTime(), alarmNotifyRequest.getExecuteTimeOut()); larkAlarmTimoutReplaceTxt = String.format(larkAlarmTimoutReplaceTxt, alarmNotifyRequest.getExecuteTime(), alarmNotifyRequest.getExecuteTimeOut());
larkAlarmTxt = StrUtil.replace(LARK_ALARM_JSON_STR, LARK_ALARM_TIMOUT_REPLACE_TXT, larkAlarmTimoutReplaceTxt); larkAlarmTxt = StrUtil.replace(LARK_ALARM_JSON_STR, LARK_ALARM_TIMOUT_REPLACE_TXT, larkAlarmTimoutReplaceTxt);
} else { } else {
@ -115,7 +113,6 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
DateUtil.now(), DateUtil.now(),
// 报警频率 // 报警频率
notifyConfig.getInterval()); notifyConfig.getInterval());
execute(notifyConfig.getSecretKey(), text); execute(notifyConfig.getSecretKey(), text);
} }
@ -125,10 +122,6 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
String threadPoolId = changeParameterNotifyRequest.getThreadPoolId(); String threadPoolId = changeParameterNotifyRequest.getThreadPoolId();
String afterReceives = getReceives(notifyConfig.getReceives()); String afterReceives = getReceives(notifyConfig.getReceives());
String larkNoticeJson = LARK_NOTICE_JSON_STR; String larkNoticeJson = LARK_NOTICE_JSON_STR;
/**
* hesitant e.g.
*/
String text = String.format(larkNoticeJson, String text = String.format(larkNoticeJson,
// 环境 // 环境
changeParameterNotifyRequest.getActive(), changeParameterNotifyRequest.getActive(),
@ -159,7 +152,6 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
afterReceives, afterReceives,
// 当前时间 // 当前时间
DateUtil.now()); DateUtil.now());
execute(notifyConfig.getSecretKey(), text); execute(notifyConfig.getSecretKey(), text);
} }
@ -174,12 +166,10 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
private void execute(String secretKey, String text) { private void execute(String secretKey, String text) {
String serverUrl = LARK_BOT_URL + secretKey; String serverUrl = LARK_BOT_URL + secretKey;
try { try {
HttpRequest.post(serverUrl).body(text).execute(); HttpRequest.post(serverUrl).body(text).execute();
} catch (Exception ex) { } catch (Exception ex) {
log.error("Lark failed to send message", ex); log.error("Lark failed to send message", ex);
} }
} }
} }

@ -88,5 +88,4 @@ public class WeChatAlarmConstants {
"> OWNER<@%s> \n" + "> OWNER<@%s> \n" +
"> 提示:动态线程池配置变更实时通知(无限制) \n\n" + "> 提示:动态线程池配置变更实时通知(无限制) \n\n" +
"**播报时间:%s**"; "**播报时间:%s**";
} }

@ -52,7 +52,6 @@ public class WeChatSendMessageHandler implements SendMessageHandler<AlarmNotifyR
public void sendAlarmMessage(NotifyConfigDTO notifyConfig, AlarmNotifyRequest alarmNotifyRequest) { public void sendAlarmMessage(NotifyConfigDTO notifyConfig, AlarmNotifyRequest alarmNotifyRequest) {
String[] receives = notifyConfig.getReceives().split(","); String[] receives = notifyConfig.getReceives().split(",");
String afterReceives = Joiner.on("><@").join(receives); String afterReceives = Joiner.on("><@").join(receives);
String weChatAlarmTxt; String weChatAlarmTxt;
String weChatAlarmTimoutReplaceTxt; String weChatAlarmTimoutReplaceTxt;
if (Objects.equals(alarmNotifyRequest.getNotifyTypeEnum(), NotifyTypeEnum.TIMEOUT)) { if (Objects.equals(alarmNotifyRequest.getNotifyTypeEnum(), NotifyTypeEnum.TIMEOUT)) {
@ -63,7 +62,6 @@ public class WeChatSendMessageHandler implements SendMessageHandler<AlarmNotifyR
} else { } else {
weChatAlarmTimoutReplaceTxt = StrUtil.replace(WE_CHAT_ALARM_TIMOUT_REPLACE_TXT, WE_CHAT_ALARM_TIMOUT_TRACE_REPLACE_TXT, ""); weChatAlarmTimoutReplaceTxt = StrUtil.replace(WE_CHAT_ALARM_TIMOUT_REPLACE_TXT, WE_CHAT_ALARM_TIMOUT_TRACE_REPLACE_TXT, "");
} }
weChatAlarmTimoutReplaceTxt = String.format(weChatAlarmTimoutReplaceTxt, alarmNotifyRequest.getExecuteTime(), alarmNotifyRequest.getExecuteTimeOut()); weChatAlarmTimoutReplaceTxt = String.format(weChatAlarmTimoutReplaceTxt, alarmNotifyRequest.getExecuteTime(), alarmNotifyRequest.getExecuteTimeOut());
weChatAlarmTxt = StrUtil.replace(WE_CHAT_ALARM_TXT, WE_CHAT_ALARM_TIMOUT_REPLACE_TXT, weChatAlarmTimoutReplaceTxt); weChatAlarmTxt = StrUtil.replace(WE_CHAT_ALARM_TXT, WE_CHAT_ALARM_TIMOUT_REPLACE_TXT, weChatAlarmTimoutReplaceTxt);
} else { } else {
@ -118,10 +116,8 @@ public class WeChatSendMessageHandler implements SendMessageHandler<AlarmNotifyR
@Override @Override
public void sendChangeMessage(NotifyConfigDTO notifyConfig, ChangeParameterNotifyRequest changeParameterNotifyRequest) { public void sendChangeMessage(NotifyConfigDTO notifyConfig, ChangeParameterNotifyRequest changeParameterNotifyRequest) {
String threadPoolId = changeParameterNotifyRequest.getThreadPoolId(); String threadPoolId = changeParameterNotifyRequest.getThreadPoolId();
String[] receives = notifyConfig.getReceives().split(","); String[] receives = notifyConfig.getReceives().split(",");
String afterReceives = Joiner.on("><@").join(receives); String afterReceives = Joiner.on("><@").join(receives);
String text = String.format( String text = String.format(
WE_CHAT_NOTICE_TXT, WE_CHAT_NOTICE_TXT,
// 环境 // 环境
@ -153,7 +149,6 @@ public class WeChatSendMessageHandler implements SendMessageHandler<AlarmNotifyR
afterReceives, afterReceives,
// 当前时间 // 当前时间
DateUtil.now()); DateUtil.now());
execute(notifyConfig.getSecretKey(), text); execute(notifyConfig.getSecretKey(), text);
} }
@ -165,15 +160,12 @@ public class WeChatSendMessageHandler implements SendMessageHandler<AlarmNotifyR
*/ */
private void execute(String secretKey, String text) { private void execute(String secretKey, String text) {
String serverUrl = WE_CHAT_SERVER_URL + secretKey; String serverUrl = WE_CHAT_SERVER_URL + secretKey;
try { try {
WeChatReqDTO weChatReq = new WeChatReqDTO(); WeChatReqDTO weChatReq = new WeChatReqDTO();
weChatReq.setMsgtype("markdown"); weChatReq.setMsgtype("markdown");
Markdown markdown = new Markdown(); Markdown markdown = new Markdown();
markdown.setContent(text); markdown.setContent(text);
weChatReq.setMarkdown(markdown); weChatReq.setMarkdown(markdown);
HttpRequest.post(serverUrl).body(JSONUtil.toJSONString(weChatReq)).execute(); HttpRequest.post(serverUrl).body(JSONUtil.toJSONString(weChatReq)).execute();
} catch (Exception ex) { } catch (Exception ex) {
log.error("WeChat failed to send message", ex); log.error("WeChat failed to send message", ex);
@ -184,26 +176,14 @@ public class WeChatSendMessageHandler implements SendMessageHandler<AlarmNotifyR
@Accessors(chain = true) @Accessors(chain = true)
public static class WeChatReqDTO { public static class WeChatReqDTO {
/**
* msgType
*/
private String msgtype; private String msgtype;
/**
* markdown
*/
private Markdown markdown; private Markdown markdown;
} }
@Data @Data
public static class Markdown { public static class Markdown {
/**
* content
*/
private String content; private String content;
} }
} }

@ -131,5 +131,4 @@ public class AlarmNotifyRequest extends BaseNotifyRequest {
* executeTimeoutTrace * executeTimeoutTrace
*/ */
private String executeTimeoutTrace; private String executeTimeoutTrace;
} }

@ -64,5 +64,4 @@ public class ChangeParameterNotifyRequest extends BaseNotifyRequest {
private String beforeRejectedName; private String beforeRejectedName;
private String nowRejectedName; private String nowRejectedName;
} }

@ -32,5 +32,4 @@ public class RobotAlarmNotifyRequest extends AlarmNotifyRequest {
* secretKey * secretKey
*/ */
private String secretKey; private String secretKey;
} }

@ -32,5 +32,4 @@ public class RobotChangeParameterNotifyRequest extends ChangeParameterNotifyRequ
* secretKey * secretKey
*/ */
private String secretKey; private String secretKey;
} }

@ -36,5 +36,4 @@ public class ThreadPoolNotifyRequest {
* groupKeys * groupKeys
*/ */
private List<String> groupKeys; private List<String> groupKeys;
} }

@ -57,5 +57,4 @@ public class BaseNotifyRequest implements NotifyRequest {
* receives * receives
*/ */
private String receives; private String receives;
} }

@ -67,7 +67,6 @@ public class ArrayUtil {
} }
} }
} }
return null; return null;
} }
@ -115,5 +114,4 @@ public class ArrayUtil {
} }
return array.clone(); return array.clone();
} }
} }

@ -25,12 +25,6 @@ package cn.hippo4j.common.toolkit;
*/ */
public class ByteConvertUtil { public class ByteConvertUtil {
/**
* .
*
* @param size
* @return
*/
public static String getPrintSize(long size) { public static String getPrintSize(long size) {
long covertNum = 1024; long covertNum = 1024;
if (size < covertNum) { if (size < covertNum) {
@ -51,5 +45,4 @@ public class ByteConvertUtil {
return (size / 100) + "." + (size % 100) + "GB"; return (size / 100) + "." + (size % 100) + "GB";
} }
} }
} }

@ -125,5 +125,4 @@ public class CollectionUtil {
public static boolean isNotEmpty(Collection<?> collection) { public static boolean isNotEmpty(Collection<?> collection) {
return !isEmpty(collection); return !isEmpty(collection);
} }
} }

@ -34,5 +34,4 @@ public class ConditionUtil {
falseConsumer.accept(); falseConsumer.accept();
} }
} }
} }

@ -62,13 +62,10 @@ public class ContentUtil {
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < parameters.length; i++) { for (int i = 0; i < parameters.length; i++) {
stringBuilder.append(parameters[i]); stringBuilder.append(parameters[i]);
if (i < parameters.length - 1) { if (i < parameters.length - 1) {
stringBuilder.append(Constants.GROUP_KEY_DELIMITER); stringBuilder.append(Constants.GROUP_KEY_DELIMITER);
} }
} }
return stringBuilder.toString(); return stringBuilder.toString();
} }
} }

@ -41,11 +41,9 @@ public class GroupKey {
public static String getKey(String... params) { public static String getKey(String... params) {
StringBuilder groupKey = new StringBuilder(); StringBuilder groupKey = new StringBuilder();
groupKey.append(params[0]).append(GROUP_KEY_DELIMITER); groupKey.append(params[0]).append(GROUP_KEY_DELIMITER);
for (int i = 1; i < params.length - 1; i++) { for (int i = 1; i < params.length - 1; i++) {
groupKey.append(params[i]).append(GROUP_KEY_DELIMITER); groupKey.append(params[i]).append(GROUP_KEY_DELIMITER);
} }
groupKey.append(params[params.length]); groupKey.append(params[params.length]);
return groupKey.toString(); return groupKey.toString();
} }
@ -63,7 +61,6 @@ public class GroupKey {
sb.append(GROUP_KEY_DELIMITER); sb.append(GROUP_KEY_DELIMITER);
urlEncode(datumStr, sb); urlEncode(datumStr, sb);
} }
return sb.toString(); return sb.toString();
} }
@ -83,5 +80,4 @@ public class GroupKey {
} }
} }
} }
} }

@ -54,5 +54,4 @@ public class JSONUtil {
return JSON_FACADE.parseArray(text, clazz); return JSON_FACADE.parseArray(text, clazz);
} }
} }

@ -70,5 +70,4 @@ public class JacksonHandler implements JsonFacade {
CollectionType collectionType = MAPPER.getTypeFactory().constructCollectionType(ArrayList.class, clazz); CollectionType collectionType = MAPPER.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
return MAPPER.readValue(text, collectionType); return MAPPER.readValue(text, collectionType);
} }
} }

@ -67,12 +67,10 @@ public class Md5Util {
public static String encodeHexString(byte[] bytes) { public static String encodeHexString(byte[] bytes) {
int l = bytes.length; int l = bytes.length;
char[] out = new char[l << 1]; char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) { for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS_LOWER[(0xF0 & bytes[i]) >>> 4]; out[j++] = DIGITS_LOWER[(0xF0 & bytes[i]) >>> 4];
out[j++] = DIGITS_LOWER[0x0F & bytes[i]]; out[j++] = DIGITS_LOWER[0x0F & bytes[i]];
} }
return new String(out); return new String(out);
} }
@ -84,9 +82,7 @@ public class Md5Util {
if (null == changedGroupKeys) { if (null == changedGroupKeys) {
return ""; return "";
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String groupKey : changedGroupKeys) { for (String groupKey : changedGroupKeys) {
String[] dataIdGroupId = GroupKey.parseKey(groupKey); String[] dataIdGroupId = GroupKey.parseKey(groupKey);
sb.append(dataIdGroupId[0]); sb.append(dataIdGroupId[0]);
@ -106,9 +102,7 @@ public class Md5Util {
} }
sb.append(Constants.LINE_SEPARATOR); sb.append(Constants.LINE_SEPARATOR);
} }
// To encode WORD_SEPARATOR and LINE_SEPARATOR invisible characters, encoded value is %02 and %01 // To encode WORD_SEPARATOR and LINE_SEPARATOR invisible characters, encoded value is %02 and %01
return URLEncoder.encode(sb.toString(), "UTF-8"); return URLEncoder.encode(sb.toString(), "UTF-8");
} }
} }

@ -44,7 +44,6 @@ public class MessageConvert {
MessageWrapper wrapper = new MessageWrapper(); MessageWrapper wrapper = new MessageWrapper();
wrapper.setResponseClass(message.getClass()); wrapper.setResponseClass(message.getClass());
wrapper.setMessageType(message.getMessageType()); wrapper.setMessageType(message.getMessageType());
List<Map<String, Object>> messageMapList = new ArrayList(); List<Map<String, Object>> messageMapList = new ArrayList();
List<Message> messages = message.getMessages(); List<Message> messages = message.getMessages();
messages.forEach(each -> { messages.forEach(each -> {
@ -52,7 +51,6 @@ public class MessageConvert {
Map mapObj = JSONUtil.parseObject(eachVal, Map.class); Map mapObj = JSONUtil.parseObject(eachVal, Map.class);
messageMapList.add(mapObj); messageMapList.add(mapObj);
}); });
wrapper.setContentParams(messageMapList); wrapper.setContentParams(messageMapList);
return wrapper; return wrapper;
} }
@ -67,17 +65,14 @@ public class MessageConvert {
public static Message convert(MessageWrapper messageWrapper) { public static Message convert(MessageWrapper messageWrapper) {
AbstractMessage message = (AbstractMessage) messageWrapper.getResponseClass().newInstance(); AbstractMessage message = (AbstractMessage) messageWrapper.getResponseClass().newInstance();
List<Map<String, Object>> contentParams = messageWrapper.getContentParams(); List<Map<String, Object>> contentParams = messageWrapper.getContentParams();
List<Message> messages = new ArrayList(); List<Message> messages = new ArrayList();
contentParams.forEach(each -> { contentParams.forEach(each -> {
String eachVal = JSONUtil.toJSONString(each); String eachVal = JSONUtil.toJSONString(each);
Message messageObj = JSONUtil.parseObject(eachVal, messageWrapper.getResponseClass()); Message messageObj = JSONUtil.parseObject(eachVal, messageWrapper.getResponseClass());
messages.add(messageObj); messages.add(messageObj);
}); });
message.setMessages(messages); message.setMessages(messages);
message.setMessageType(messageWrapper.getMessageType()); message.setMessageType(messageWrapper.getMessageType());
return message; return message;
} }
} }

@ -37,7 +37,6 @@ public class ReflectUtil {
if (null == obj || StringUtil.isBlank(fieldName)) { if (null == obj || StringUtil.isBlank(fieldName)) {
return null; return null;
} }
Field field = getField(obj instanceof Class ? (Class<?>) obj : obj.getClass(), fieldName); Field field = getField(obj instanceof Class ? (Class<?>) obj : obj.getClass(), fieldName);
return getFieldValue(obj, field); return getFieldValue(obj, field);
} }
@ -49,7 +48,6 @@ public class ReflectUtil {
if (obj instanceof Class) { if (obj instanceof Class) {
obj = null; obj = null;
} }
setAccessible(field); setAccessible(field);
Object result; Object result;
try { try {
@ -58,7 +56,6 @@ public class ReflectUtil {
String exceptionMsg = String.format("IllegalAccess for %s.%s", field.getDeclaringClass(), field.getName()); String exceptionMsg = String.format("IllegalAccess for %s.%s", field.getDeclaringClass(), field.getName());
throw new RuntimeException(exceptionMsg, e); throw new RuntimeException(exceptionMsg, e);
} }
return result; return result;
} }
@ -79,7 +76,6 @@ public class ReflectUtil {
if (null != allFields) { if (null != allFields) {
return allFields; return allFields;
} }
allFields = getFieldsDirectly(beanClass, true); allFields = getFieldsDirectly(beanClass, true);
FIELDS_CACHE.put(beanClass, allFields); FIELDS_CACHE.put(beanClass, allFields);
return allFields; return allFields;
@ -87,7 +83,6 @@ public class ReflectUtil {
public static Field[] getFieldsDirectly(Class<?> beanClass, boolean withSuperClassFields) throws SecurityException { public static Field[] getFieldsDirectly(Class<?> beanClass, boolean withSuperClassFields) throws SecurityException {
Assert.notNull(beanClass); Assert.notNull(beanClass);
Field[] allFields = null; Field[] allFields = null;
Class<?> searchType = beanClass; Class<?> searchType = beanClass;
Field[] declaredFields; Field[] declaredFields;
@ -112,8 +107,6 @@ public class ReflectUtil {
if (null == field) { if (null == field) {
return null; return null;
} }
return field.getName(); return field.getName();
} }
} }

@ -37,20 +37,16 @@ public class StringUtil {
*/ */
public static boolean isBlank(CharSequence str) { public static boolean isBlank(CharSequence str) {
int length; int length;
if ((str == null) || ((length = str.length()) == 0)) { if ((str == null) || ((length = str.length()) == 0)) {
return true; return true;
} }
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
char c = str.charAt(i); char c = str.charAt(i);
boolean charNotBlank = Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\ufeff' || c == '\u202a'; boolean charNotBlank = Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\ufeff' || c == '\u202a';
if (charNotBlank == false) { if (charNotBlank == false) {
return false; return false;
} }
} }
return true; return true;
} }
@ -163,8 +159,6 @@ public class StringUtil {
sb.append(c); sb.append(c);
} }
} }
return sb.toString(); return sb.toString();
} }
} }

@ -26,11 +26,11 @@ package cn.hippo4j.common.toolkit;
public class ThreadUtil { public class ThreadUtil {
/** /**
* 线. * New thread.
* *
* @param runnable {@link Runnable} * @param runnable
* @param name 线 * @param name
* @param isDaemon 线 * @param isDaemon
* @return {@link Thread} * @return {@link Thread}
*/ */
public static Thread newThread(Runnable runnable, String name, boolean isDaemon) { public static Thread newThread(Runnable runnable, String name, boolean isDaemon) {
@ -40,9 +40,9 @@ public class ThreadUtil {
} }
/** /**
* 线. * Suspend the current thread.
* *
* @param millis * @param millis
* @return * @return
*/ */
public static boolean sleep(long millis) { public static boolean sleep(long millis) {
@ -53,8 +53,6 @@ public class ThreadUtil {
return false; return false;
} }
} }
return true; return true;
} }
} }

@ -57,7 +57,5 @@ public class UserContext {
private String username; private String username;
private String userRole; private String userRole;
} }
} }

@ -62,5 +62,4 @@ public class Result<T> implements Serializable {
public boolean isSuccess() { public boolean isSuccess() {
return SUCCESS_CODE.equals(code); return SUCCESS_CODE.equals(code);
} }
} }

@ -31,44 +31,21 @@ import java.util.Optional;
*/ */
public final class Results { public final class Results {
/**
* .
*
* @return
*/
public static Result<Void> success() { public static Result<Void> success() {
return new Result<Void>() return new Result<Void>()
.setCode(Result.SUCCESS_CODE); .setCode(Result.SUCCESS_CODE);
} }
/**
* .
*
* @param data DATA
* @param <T> DATA
* @return
*/
public static <T> Result<T> success(T data) { public static <T> Result<T> success(T data) {
return new Result<T>() return new Result<T>()
.setCode(Result.SUCCESS_CODE) .setCode(Result.SUCCESS_CODE)
.setData(data); .setData(data);
} }
/**
* .
*
* @return
*/
public static Result<Void> failure() { public static Result<Void> failure() {
return failure(ErrorCodeEnum.SERVICE_ERROR.getCode(), ErrorCodeEnum.SERVICE_ERROR.getMessage()); return failure(ErrorCodeEnum.SERVICE_ERROR.getCode(), ErrorCodeEnum.SERVICE_ERROR.getMessage());
} }
/**
* .
*
* @param abstractException
* @return
*/
public static Result<Void> failure(AbstractException abstractException) { public static Result<Void> failure(AbstractException abstractException) {
String errorCode = Optional.ofNullable(abstractException.getErrorCode()) String errorCode = Optional.ofNullable(abstractException.getErrorCode())
.map(ErrorCode::getCode) .map(ErrorCode::getCode)
@ -78,38 +55,18 @@ public final class Results {
.setMessage(abstractException.getMessage()); .setMessage(abstractException.getMessage());
} }
/**
* .
*
* @param throwable
* @return
*/
public static Result<Void> failure(Throwable throwable) { public static Result<Void> failure(Throwable throwable) {
return new Result<Void>().setCode(ErrorCodeEnum.SERVICE_ERROR.getCode()) return new Result<Void>().setCode(ErrorCodeEnum.SERVICE_ERROR.getCode())
.setMessage(throwable.getMessage()); .setMessage(throwable.getMessage());
} }
/**
* .
*
* @param errorCode
* @return
*/
public static Result<Void> failure(ErrorCode errorCode) { public static Result<Void> failure(ErrorCode errorCode) {
return failure(errorCode.getCode(), errorCode.getMessage()); return failure(errorCode.getCode(), errorCode.getMessage());
} }
/**
* .
*
* @param code .
* @param message .
* @return
*/
public static Result<Void> failure(String code, String message) { public static Result<Void> failure(String code, String message) {
return new Result<Void>() return new Result<Void>()
.setCode(code) .setCode(code)
.setMessage(message); .setMessage(message);
} }
} }

@ -34,5 +34,4 @@ public class AbstractException extends RuntimeException {
super(message, throwable); super(message, throwable);
this.errorCode = errorCode; this.errorCode = errorCode;
} }
} }

@ -18,7 +18,7 @@
package cn.hippo4j.common.web.exception; package cn.hippo4j.common.web.exception;
/** /**
* . * Error code abstract interface.
* *
* @author chen.ma * @author chen.ma
* @date 2021/9/16 15:39 * @date 2021/9/16 15:39
@ -26,17 +26,16 @@ package cn.hippo4j.common.web.exception;
public interface ErrorCode { public interface ErrorCode {
/** /**
* . * Get code.
* *
* @return * @return
*/ */
String getCode(); String getCode();
/** /**
* . * Get message.
* *
* @return * @return
*/ */
String getMessage(); String getMessage();
} }

@ -99,5 +99,4 @@ public enum ErrorCodeEnum implements ErrorCode {
return "登录时间过长, 请退出重新登录"; return "登录时间过长, 请退出重新登录";
} }
} }
} }

@ -28,78 +28,34 @@ import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class ServiceException extends AbstractException { public class ServiceException extends AbstractException {
/**
* .
*/
public ServiceException() { public ServiceException() {
this(ErrorCodeEnum.SERVICE_ERROR); this(ErrorCodeEnum.SERVICE_ERROR);
} }
/**
* .
*
* @param errorCode
*/
public ServiceException(ErrorCode errorCode) { public ServiceException(ErrorCode errorCode) {
this(errorCode.getMessage(), null, errorCode); this(errorCode.getMessage(), null, errorCode);
} }
/**
* .
*
* @param message
*/
public ServiceException(String message) { public ServiceException(String message) {
this(message, null, ErrorCodeEnum.SERVICE_ERROR); this(message, null, ErrorCodeEnum.SERVICE_ERROR);
} }
/**
* .
*
* @param cause
*/
public ServiceException(Throwable cause) { public ServiceException(Throwable cause) {
this(cause, cause.getMessage()); this(cause, cause.getMessage());
} }
/**
* .
*
* @param message
* @param cause
*/
public ServiceException(String message, Throwable cause) { public ServiceException(String message, Throwable cause) {
this(message, cause, ErrorCodeEnum.SERVICE_ERROR); this(message, cause, ErrorCodeEnum.SERVICE_ERROR);
} }
/**
* .
*
* @param cause
* @param message
*/
public ServiceException(Throwable cause, String message) { public ServiceException(Throwable cause, String message) {
this(message, cause, ErrorCodeEnum.SERVICE_ERROR); this(message, cause, ErrorCodeEnum.SERVICE_ERROR);
} }
/**
* .
*
* @param cause
* @param errorCode
*/
public ServiceException(Throwable cause, ErrorCode errorCode) { public ServiceException(Throwable cause, ErrorCode errorCode) {
this(errorCode.getMessage(), cause, errorCode); this(errorCode.getMessage(), cause, errorCode);
} }
/**
* , .
* <p> , .
*
* @param message
* @param cause
* @param errorCode
*/
public ServiceException(String message, Throwable cause, ErrorCode errorCode) { public ServiceException(String message, Throwable cause, ErrorCode errorCode) {
super(message, cause, errorCode); super(message, cause, errorCode);
} }
@ -111,5 +67,4 @@ public class ServiceException extends AbstractException {
"message='" + errorCode.getMessage() + "'" + "message='" + errorCode.getMessage() + "'" +
'}'; '}';
} }
} }

@ -30,27 +30,12 @@ import java.util.concurrent.ConcurrentHashMap;
*/ */
public class GlobalNotifyAlarmManage { public class GlobalNotifyAlarmManage {
/**
* Notify alarm map.
*/
private static final Map<String, ThreadPoolNotifyAlarm> NOTIFY_ALARM_MAP = new ConcurrentHashMap(); private static final Map<String, ThreadPoolNotifyAlarm> NOTIFY_ALARM_MAP = new ConcurrentHashMap();
/**
* Get.
*
* @param key
* @return
*/
public static ThreadPoolNotifyAlarm get(String key) { public static ThreadPoolNotifyAlarm get(String key) {
return NOTIFY_ALARM_MAP.get(key); return NOTIFY_ALARM_MAP.get(key);
} }
/**
* Put.
*
* @param key
* @param val
*/
public static void put(String key, ThreadPoolNotifyAlarm val) { public static void put(String key, ThreadPoolNotifyAlarm val) {
NOTIFY_ALARM_MAP.put(key, val); NOTIFY_ALARM_MAP.put(key, val);
} }

@ -26,7 +26,7 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* Global threadPool manage. * Global thread-pool manage.
* *
* @author chen.ma * @author chen.ma
* @date 2021/6/20 15:57 * @date 2021/6/20 15:57
@ -34,17 +34,17 @@ import java.util.concurrent.ConcurrentHashMap;
public class GlobalThreadPoolManage { public class GlobalThreadPoolManage {
/** /**
* 线. * Dynamic thread pool parameter container.
*/ */
private static final Map<String, PoolParameter> POOL_PARAMETER = new ConcurrentHashMap(); private static final Map<String, PoolParameter> POOL_PARAMETER = new ConcurrentHashMap();
/** /**
* 线. * Dynamic thread pool wrapper.
*/ */
private static final Map<String, DynamicThreadPoolWrapper> EXECUTOR_MAP = new ConcurrentHashMap(); private static final Map<String, DynamicThreadPoolWrapper> EXECUTOR_MAP = new ConcurrentHashMap();
/** /**
* 线. * Get the dynamic thread pool wrapper class.
* *
* @param threadPoolId * @param threadPoolId
* @return * @return
@ -54,7 +54,7 @@ public class GlobalThreadPoolManage {
} }
/** /**
* 线. * Get dynamic thread pool parameters.
* *
* @param threadPoolId * @param threadPoolId
* @return * @return
@ -64,7 +64,7 @@ public class GlobalThreadPoolManage {
} }
/** /**
* 线. * Register dynamic thread pool wrapper and parameters.
* *
* @param threadPoolId * @param threadPoolId
* @param poolParameter * @param poolParameter
@ -76,7 +76,7 @@ public class GlobalThreadPoolManage {
} }
/** /**
* 线. * Register dynamic thread pool.
* *
* @param threadPoolId * @param threadPoolId
* @param executor * @param executor
@ -86,7 +86,7 @@ public class GlobalThreadPoolManage {
} }
/** /**
* 线. * Register dynamic thread pool parameters.
* *
* @param threadPoolId * @param threadPoolId
* @param poolParameter * @param poolParameter
@ -96,7 +96,7 @@ public class GlobalThreadPoolManage {
} }
/** /**
* 线. * Get the dynamic thread pool identifier collection.
* *
* @return * @return
*/ */
@ -105,8 +105,10 @@ public class GlobalThreadPoolManage {
} }
/** /**
* 线. * Get the number of dynamic thread pools.
* , . *
* The data may be inaccurate when the project is initially
* launched because registration is done asynchronously.
* *
* @return * @return
*/ */

@ -58,11 +58,6 @@ public class AbstractBuildThreadPoolTemplate {
return buildPool(initParam); return buildPool(initParam);
} }
/**
* 线.
*
* @return
*/
public static ThreadPoolExecutor buildPool(ThreadPoolInitParam initParam) { public static ThreadPoolExecutor buildPool(ThreadPoolInitParam initParam) {
Assert.notNull(initParam); Assert.notNull(initParam);
ThreadPoolExecutor executorService; ThreadPoolExecutor executorService;
@ -81,21 +76,11 @@ public class AbstractBuildThreadPoolTemplate {
return executorService; return executorService;
} }
/**
* 线.
*
* @return
*/
public static ThreadPoolExecutor buildFastPool() { public static ThreadPoolExecutor buildFastPool() {
ThreadPoolInitParam initParam = initParam(); ThreadPoolInitParam initParam = initParam();
return buildFastPool(initParam); return buildFastPool(initParam);
} }
/**
* 线.
*
* @return
*/
public static ThreadPoolExecutor buildFastPool(ThreadPoolInitParam initParam) { public static ThreadPoolExecutor buildFastPool(ThreadPoolInitParam initParam) {
TaskQueue<Runnable> taskQueue = new TaskQueue(initParam.getCapacity()); TaskQueue<Runnable> taskQueue = new TaskQueue(initParam.getCapacity());
FastThreadPoolExecutor fastThreadPoolExecutor; FastThreadPoolExecutor fastThreadPoolExecutor;
@ -115,12 +100,6 @@ public class AbstractBuildThreadPoolTemplate {
return fastThreadPoolExecutor; return fastThreadPoolExecutor;
} }
/**
* 线.
*
* @param initParam
* @return
*/
public static DynamicThreadPoolExecutor buildDynamicPool(ThreadPoolInitParam initParam) { public static DynamicThreadPoolExecutor buildDynamicPool(ThreadPoolInitParam initParam) {
Assert.notNull(initParam); Assert.notNull(initParam);
DynamicThreadPoolExecutor dynamicThreadPoolExecutor; DynamicThreadPoolExecutor dynamicThreadPoolExecutor;
@ -149,74 +128,32 @@ public class AbstractBuildThreadPoolTemplate {
@Accessors(chain = true) @Accessors(chain = true)
public static class ThreadPoolInitParam { public static class ThreadPoolInitParam {
/**
* 线
*/
private Integer corePoolNum; private Integer corePoolNum;
/**
* 线
*/
private Integer maxPoolNum; private Integer maxPoolNum;
/**
* 线
*/
private Long keepAliveTime; private Long keepAliveTime;
/**
* 线
*/
private TimeUnit timeUnit; private TimeUnit timeUnit;
/**
*
*/
private Long executeTimeOut; private Long executeTimeOut;
/**
*
*/
private Integer capacity; private Integer capacity;
/**
*
*/
private BlockingQueue<Runnable> workQueue; private BlockingQueue<Runnable> workQueue;
/**
* 线
*/
private RejectedExecutionHandler rejectedExecutionHandler; private RejectedExecutionHandler rejectedExecutionHandler;
/**
* 线
*/
private ThreadFactory threadFactory; private ThreadFactory threadFactory;
/**
* 线 ID
*/
private String threadPoolId; private String threadPoolId;
/**
* 线
*/
private TaskDecorator taskDecorator; private TaskDecorator taskDecorator;
/**
*
*/
private Long awaitTerminationMillis; private Long awaitTerminationMillis;
/**
*
*/
private Boolean waitForTasksToCompleteOnShutdown; private Boolean waitForTasksToCompleteOnShutdown;
/**
* 线
*/
private Boolean allowCoreThreadTimeOut = false; private Boolean allowCoreThreadTimeOut = false;
public ThreadPoolInitParam(String threadNamePrefix, boolean isDaemon) { public ThreadPoolInitParam(String threadNamePrefix, boolean isDaemon) {

@ -30,10 +30,7 @@ import java.util.concurrent.*;
* @date 2021/11/28 12:17 * @date 2021/11/28 12:17
*/ */
@Slf4j @Slf4j
public abstract class AbstractDynamicExecutorSupport extends ThreadPoolExecutor public abstract class AbstractDynamicExecutorSupport extends ThreadPoolExecutor implements InitializingBean, DisposableBean {
implements
InitializingBean,
DisposableBean {
private String threadPoolId; private String threadPoolId;

@ -29,12 +29,6 @@ import java.util.concurrent.TimeUnit;
*/ */
public class CommonDynamicThreadPool { public class CommonDynamicThreadPool {
/**
* Get instance.
*
* @param threadPoolId
* @return
*/
public static DynamicThreadPoolExecutor getInstance(String threadPoolId) { public static DynamicThreadPoolExecutor getInstance(String threadPoolId) {
DynamicThreadPoolExecutor poolExecutor = (DynamicThreadPoolExecutor) ThreadPoolBuilder.builder() DynamicThreadPoolExecutor poolExecutor = (DynamicThreadPoolExecutor) ThreadPoolBuilder.builder()
.dynamicPool() .dynamicPool()

@ -83,13 +83,6 @@ public enum QueueTypeEnum {
DynamicThreadPoolServiceLoader.register(CustomBlockingQueue.class); DynamicThreadPoolServiceLoader.register(CustomBlockingQueue.class);
} }
/**
* Create blocking queue.
*
* @param blockingQueueName
* @param capacity
* @return
*/
public static BlockingQueue createBlockingQueue(String blockingQueueName, Integer capacity) { public static BlockingQueue createBlockingQueue(String blockingQueueName, Integer capacity) {
BlockingQueue blockingQueue = null; BlockingQueue blockingQueue = null;
QueueTypeEnum queueTypeEnum = Stream.of(QueueTypeEnum.values()) QueueTypeEnum queueTypeEnum = Stream.of(QueueTypeEnum.values())
@ -121,13 +114,6 @@ public enum QueueTypeEnum {
return blockingQueue; return blockingQueue;
} }
/**
* Create blocking queue.
*
* @param type
* @param capacity
* @return
*/
public static BlockingQueue createBlockingQueue(int type, Integer capacity) { public static BlockingQueue createBlockingQueue(int type, Integer capacity) {
BlockingQueue blockingQueue = null; BlockingQueue blockingQueue = null;
if (Objects.equals(type, ARRAY_BLOCKING_QUEUE.type)) { if (Objects.equals(type, ARRAY_BLOCKING_QUEUE.type)) {
@ -155,12 +141,6 @@ public enum QueueTypeEnum {
return blockingQueue; return blockingQueue;
} }
/**
* Get blocking queue name by type.
*
* @param type
* @return
*/
public static String getBlockingQueueNameByType(int type) { public static String getBlockingQueueNameByType(int type) {
Optional<QueueTypeEnum> queueTypeEnum = Arrays.stream(QueueTypeEnum.values()) Optional<QueueTypeEnum> queueTypeEnum = Arrays.stream(QueueTypeEnum.values())
.filter(each -> each.type == type) .filter(each -> each.type == type)

@ -32,9 +32,6 @@ import java.util.concurrent.ThreadPoolExecutor;
@Slf4j @Slf4j
public class RejectedPolicies { public class RejectedPolicies {
/**
* , .
*/
public static class RunsOldestTaskPolicy implements RejectedExecutionHandler { public static class RunsOldestTaskPolicy implements RejectedExecutionHandler {
@Override @Override
@ -54,9 +51,6 @@ public class RejectedPolicies {
} }
} }
/**
* 使, .
*/
public static class SyncPutQueuePolicy implements RejectedExecutionHandler { public static class SyncPutQueuePolicy implements RejectedExecutionHandler {
@Override @Override

@ -35,49 +35,22 @@ import java.util.stream.Stream;
*/ */
public enum RejectedTypeEnum { public enum RejectedTypeEnum {
/**
* 线
*/
CALLER_RUNS_POLICY(1, "CallerRunsPolicy", new ThreadPoolExecutor.CallerRunsPolicy()), CALLER_RUNS_POLICY(1, "CallerRunsPolicy", new ThreadPoolExecutor.CallerRunsPolicy()),
/**
* ,
*/
ABORT_POLICY(2, "AbortPolicy", new ThreadPoolExecutor.AbortPolicy()), ABORT_POLICY(2, "AbortPolicy", new ThreadPoolExecutor.AbortPolicy()),
/**
* ,
*/
DISCARD_POLICY(3, "DiscardPolicy", new ThreadPoolExecutor.DiscardPolicy()), DISCARD_POLICY(3, "DiscardPolicy", new ThreadPoolExecutor.DiscardPolicy()),
/**
* , ,
*/
DISCARD_OLDEST_POLICY(4, "DiscardOldestPolicy", new ThreadPoolExecutor.DiscardOldestPolicy()), DISCARD_OLDEST_POLICY(4, "DiscardOldestPolicy", new ThreadPoolExecutor.DiscardOldestPolicy()),
/**
* ,
*/
RUNS_OLDEST_TASK_POLICY(5, "RunsOldestTaskPolicy", new RejectedPolicies.RunsOldestTaskPolicy()), RUNS_OLDEST_TASK_POLICY(5, "RunsOldestTaskPolicy", new RejectedPolicies.RunsOldestTaskPolicy()),
/**
* 使,
*/
SYNC_PUT_QUEUE_POLICY(6, "SyncPutQueuePolicy", new RejectedPolicies.SyncPutQueuePolicy()); SYNC_PUT_QUEUE_POLICY(6, "SyncPutQueuePolicy", new RejectedPolicies.SyncPutQueuePolicy());
/**
*
*/
public Integer type; public Integer type;
/**
*
*/
public String name; public String name;
/**
* 线
*/
public RejectedExecutionHandler rejectedHandler; public RejectedExecutionHandler rejectedHandler;
RejectedTypeEnum(Integer type, String name, RejectedExecutionHandler rejectedHandler) { RejectedTypeEnum(Integer type, String name, RejectedExecutionHandler rejectedHandler) {
@ -90,12 +63,6 @@ public enum RejectedTypeEnum {
DynamicThreadPoolServiceLoader.register(CustomRejectedExecutionHandler.class); DynamicThreadPoolServiceLoader.register(CustomRejectedExecutionHandler.class);
} }
/**
* Create policy.
*
* @param name
* @return
*/
public static RejectedExecutionHandler createPolicy(String name) { public static RejectedExecutionHandler createPolicy(String name) {
RejectedTypeEnum rejectedTypeEnum = Stream.of(RejectedTypeEnum.values()) RejectedTypeEnum rejectedTypeEnum = Stream.of(RejectedTypeEnum.values())
.filter(each -> Objects.equals(each.name, name)) .filter(each -> Objects.equals(each.name, name))
@ -113,18 +80,11 @@ public enum RejectedTypeEnum {
return customRejected.orElse(ABORT_POLICY.rejectedHandler); return customRejected.orElse(ABORT_POLICY.rejectedHandler);
} }
/**
* Create policy.
*
* @param type
* @return
*/
public static RejectedExecutionHandler createPolicy(int type) { public static RejectedExecutionHandler createPolicy(int type) {
Optional<RejectedExecutionHandler> rejectedTypeEnum = Stream.of(RejectedTypeEnum.values()) Optional<RejectedExecutionHandler> rejectedTypeEnum = Stream.of(RejectedTypeEnum.values())
.filter(each -> Objects.equals(type, each.type)) .filter(each -> Objects.equals(type, each.type))
.map(each -> each.rejectedHandler) .map(each -> each.rejectedHandler)
.findFirst(); .findFirst();
// 使用 SPI 匹配拒绝策略
RejectedExecutionHandler resultRejected = rejectedTypeEnum.orElseGet(() -> { RejectedExecutionHandler resultRejected = rejectedTypeEnum.orElseGet(() -> {
Collection<CustomRejectedExecutionHandler> customRejectedExecutionHandlers = DynamicThreadPoolServiceLoader Collection<CustomRejectedExecutionHandler> customRejectedExecutionHandlers = DynamicThreadPoolServiceLoader
.getSingletonServiceInstances(CustomRejectedExecutionHandler.class); .getSingletonServiceInstances(CustomRejectedExecutionHandler.class);
@ -137,12 +97,6 @@ public enum RejectedTypeEnum {
return resultRejected; return resultRejected;
} }
/**
* Get rejected name by type.
*
* @param type
* @return
*/
public static String getRejectedNameByType(int type) { public static String getRejectedNameByType(int type) {
return createPolicy(type).getClass().getSimpleName(); return createPolicy(type).getClass().getSimpleName();
} }

@ -24,7 +24,7 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
/** /**
* Resizable capacity linkedBlockIngQueue. * Resizable capacity linked-blocking-queue.
* *
* @author chen.ma * @author chen.ma
* @date 2021/6/20 14:24 * @date 2021/6/20 14:24

@ -24,7 +24,7 @@ import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
/** /**
* ThreadFactory builder. * Thread-factory builder.
* *
* @author chen.ma * @author chen.ma
* @date 2021/7/5 21:53 * @date 2021/7/5 21:53
@ -33,73 +33,31 @@ public class ThreadFactoryBuilder implements Builder<ThreadFactory> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/**
* 线线
*/
private ThreadFactory backingThreadFactory; private ThreadFactory backingThreadFactory;
/**
* 线
*/
private String namePrefix; private String namePrefix;
/**
* 线false
*/
private Boolean daemon; private Boolean daemon;
/**
* 线
*/
private Integer priority; private Integer priority;
/**
*
*/
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler; private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
/**
* 线线.
*
* @param backingThreadFactory 线线
* @return this
*/
public ThreadFactoryBuilder threadFactory(ThreadFactory backingThreadFactory) { public ThreadFactoryBuilder threadFactory(ThreadFactory backingThreadFactory) {
this.backingThreadFactory = backingThreadFactory; this.backingThreadFactory = backingThreadFactory;
return this; return this;
} }
/**
* 线, mb-thread- 线 mb-thread-1 .
*
* @param namePrefix 线
* @return this
*/
public ThreadFactoryBuilder prefix(String namePrefix) { public ThreadFactoryBuilder prefix(String namePrefix) {
this.namePrefix = namePrefix; this.namePrefix = namePrefix;
return this; return this;
} }
/**
* 线.
*
* @param daemon 线
* @return this
*/
public ThreadFactoryBuilder daemon(boolean daemon) { public ThreadFactoryBuilder daemon(boolean daemon) {
this.daemon = daemon; this.daemon = daemon;
return this; return this;
} }
/**
* 线.
*
* @param priority
* @return this
* @see Thread#MIN_PRIORITY
* @see Thread#NORM_PRIORITY
* @see Thread#MAX_PRIORITY
*/
public ThreadFactoryBuilder priority(int priority) { public ThreadFactoryBuilder priority(int priority) {
if (priority < Thread.MIN_PRIORITY) { if (priority < Thread.MIN_PRIORITY) {
throw new IllegalArgumentException(String.format("Thread priority ({}) must be >= {}", priority, Thread.MIN_PRIORITY)); throw new IllegalArgumentException(String.format("Thread priority ({}) must be >= {}", priority, Thread.MIN_PRIORITY));
@ -111,40 +69,19 @@ public class ThreadFactoryBuilder implements Builder<ThreadFactory> {
return this; return this;
} }
/**
* .
*
* @param uncaughtExceptionHandler {@link Thread.UncaughtExceptionHandler}
*/
public void uncaughtExceptionHandler(Thread.UncaughtExceptionHandler uncaughtExceptionHandler) { public void uncaughtExceptionHandler(Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
this.uncaughtExceptionHandler = uncaughtExceptionHandler; this.uncaughtExceptionHandler = uncaughtExceptionHandler;
} }
/**
* .
*
* @return
*/
public static ThreadFactoryBuilder builder() { public static ThreadFactoryBuilder builder() {
return new ThreadFactoryBuilder(); return new ThreadFactoryBuilder();
} }
/**
* {@link ThreadFactory}
*
* @return {@link ThreadFactory}
*/
@Override @Override
public ThreadFactory build() { public ThreadFactory build() {
return build(this); return build(this);
} }
/**
* .
*
* @param builder {@link ThreadFactoryBuilder}
* @return {@link ThreadFactory}
*/
private static ThreadFactory build(ThreadFactoryBuilder builder) { private static ThreadFactory build(ThreadFactoryBuilder builder) {
final ThreadFactory backingThreadFactory = (null != builder.backingThreadFactory) final ThreadFactory backingThreadFactory = (null != builder.backingThreadFactory)
? builder.backingThreadFactory ? builder.backingThreadFactory

@ -26,110 +26,49 @@ import java.util.Optional;
import java.util.concurrent.*; import java.util.concurrent.*;
/** /**
* ThreadPool builder. * Thread-pool builder.
* *
* @author chen.ma * @author chen.ma
* @date 2021/6/28 17:29 * @date 2021/6/28 17:29
*/ */
public class ThreadPoolBuilder implements Builder<ThreadPoolExecutor> { public class ThreadPoolBuilder implements Builder<ThreadPoolExecutor> {
/**
* 线
*/
private boolean isFastPool; private boolean isFastPool;
/**
* 线
*/
private boolean isDynamicPool; private boolean isDynamicPool;
/**
* 线
*/
private int corePoolSize = calculateCoreNum(); private int corePoolSize = calculateCoreNum();
/**
* 线
*/
private int maxPoolSize = corePoolSize + (corePoolSize >> 1); private int maxPoolSize = corePoolSize + (corePoolSize >> 1);
/**
* 线
*/
private long keepAliveTime = 30000L; private long keepAliveTime = 30000L;
/**
* 线
*/
private TimeUnit timeUnit = TimeUnit.MILLISECONDS; private TimeUnit timeUnit = TimeUnit.MILLISECONDS;
/**
* 线
*/
private long executeTimeOut = 10000L; private long executeTimeOut = 10000L;
/**
*
*/
private int capacity = 512; private int capacity = 512;
/**
*
*/
private QueueTypeEnum queueType; private QueueTypeEnum queueType;
/**
*
*/
private BlockingQueue workQueue = new LinkedBlockingQueue(capacity); private BlockingQueue workQueue = new LinkedBlockingQueue(capacity);
/**
* 线
*/
private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy(); private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
/**
* 线
*/
private boolean isDaemon = false; private boolean isDaemon = false;
/**
* 线
*/
private String threadNamePrefix; private String threadNamePrefix;
/**
* 线 ID
*/
private String threadPoolId; private String threadPoolId;
/**
* 线
*/
private TaskDecorator taskDecorator; private TaskDecorator taskDecorator;
/**
*
*/
private Long awaitTerminationMillis = 5000L; private Long awaitTerminationMillis = 5000L;
/**
*
*/
private Boolean waitForTasksToCompleteOnShutdown = true; private Boolean waitForTasksToCompleteOnShutdown = true;
/**
* 线
*/
private Boolean allowCoreThreadTimeOut = false; private Boolean allowCoreThreadTimeOut = false;
private Boolean prestartCoreThread = false;
/**
* CPU / (1 - 0.8)
*
* @return 线线
*/
private Integer calculateCoreNum() { private Integer calculateCoreNum() {
int cpuCoreNum = Runtime.getRuntime().availableProcessors(); int cpuCoreNum = Runtime.getRuntime().availableProcessors();
return new BigDecimal(cpuCoreNum).divide(new BigDecimal("0.2")).intValue(); return new BigDecimal(cpuCoreNum).divide(new BigDecimal("0.2")).intValue();
@ -265,11 +204,6 @@ public class ThreadPoolBuilder implements Builder<ThreadPoolExecutor> {
return this; return this;
} }
/**
* .
*
* @return
*/
@Override @Override
public ThreadPoolExecutor build() { public ThreadPoolExecutor build() {
if (isDynamicPool) { if (isDynamicPool) {
@ -278,56 +212,26 @@ public class ThreadPoolBuilder implements Builder<ThreadPoolExecutor> {
return isFastPool ? buildFastPool(this) : buildPool(this); return isFastPool ? buildFastPool(this) : buildPool(this);
} }
/**
* .
*
* @return
*/
public static ThreadPoolBuilder builder() { public static ThreadPoolBuilder builder() {
return new ThreadPoolBuilder(); return new ThreadPoolBuilder();
} }
/**
* 线.
*
* @param builder
* @return
*/
private static ThreadPoolExecutor buildPool(ThreadPoolBuilder builder) { private static ThreadPoolExecutor buildPool(ThreadPoolBuilder builder) {
return AbstractBuildThreadPoolTemplate.buildPool(buildInitParam(builder)); return AbstractBuildThreadPoolTemplate.buildPool(buildInitParam(builder));
} }
/**
* 线.
*
* @param builder
* @return
*/
private static ThreadPoolExecutor buildFastPool(ThreadPoolBuilder builder) { private static ThreadPoolExecutor buildFastPool(ThreadPoolBuilder builder) {
return AbstractBuildThreadPoolTemplate.buildFastPool(buildInitParam(builder)); return AbstractBuildThreadPoolTemplate.buildFastPool(buildInitParam(builder));
} }
/**
* 线.
*
* @param builder
* @return
*/
private static ThreadPoolExecutor buildDynamicPool(ThreadPoolBuilder builder) { private static ThreadPoolExecutor buildDynamicPool(ThreadPoolBuilder builder) {
return AbstractBuildThreadPoolTemplate.buildDynamicPool(buildInitParam(builder)); return AbstractBuildThreadPoolTemplate.buildDynamicPool(buildInitParam(builder));
} }
/**
* .
*
* @param builder
* @return
*/
private static AbstractBuildThreadPoolTemplate.ThreadPoolInitParam buildInitParam(ThreadPoolBuilder builder) { private static AbstractBuildThreadPoolTemplate.ThreadPoolInitParam buildInitParam(ThreadPoolBuilder builder) {
Assert.notEmpty(builder.threadNamePrefix, "The thread name prefix cannot be empty or an empty string."); Assert.notEmpty(builder.threadNamePrefix, "The thread name prefix cannot be empty or an empty string.");
AbstractBuildThreadPoolTemplate.ThreadPoolInitParam initParam = AbstractBuildThreadPoolTemplate.ThreadPoolInitParam initParam =
new AbstractBuildThreadPoolTemplate.ThreadPoolInitParam(builder.threadNamePrefix, builder.isDaemon); new AbstractBuildThreadPoolTemplate.ThreadPoolInitParam(builder.threadNamePrefix, builder.isDaemon);
initParam.setCorePoolNum(builder.corePoolSize) initParam.setCorePoolNum(builder.corePoolSize)
.setMaxPoolNum(builder.maxPoolSize) .setMaxPoolNum(builder.maxPoolSize)
.setKeepAliveTime(builder.keepAliveTime) .setKeepAliveTime(builder.keepAliveTime)
@ -337,22 +241,18 @@ public class ThreadPoolBuilder implements Builder<ThreadPoolExecutor> {
.setTimeUnit(builder.timeUnit) .setTimeUnit(builder.timeUnit)
.setAllowCoreThreadTimeOut(builder.allowCoreThreadTimeOut) .setAllowCoreThreadTimeOut(builder.allowCoreThreadTimeOut)
.setTaskDecorator(builder.taskDecorator); .setTaskDecorator(builder.taskDecorator);
if (builder.isDynamicPool) { if (builder.isDynamicPool) {
String threadPoolId = Optional.ofNullable(builder.threadPoolId).orElse(builder.threadNamePrefix); String threadPoolId = Optional.ofNullable(builder.threadPoolId).orElse(builder.threadNamePrefix);
initParam.setThreadPoolId(threadPoolId); initParam.setThreadPoolId(threadPoolId);
initParam.setWaitForTasksToCompleteOnShutdown(builder.waitForTasksToCompleteOnShutdown); initParam.setWaitForTasksToCompleteOnShutdown(builder.waitForTasksToCompleteOnShutdown);
initParam.setAwaitTerminationMillis(builder.awaitTerminationMillis); initParam.setAwaitTerminationMillis(builder.awaitTerminationMillis);
} }
if (!builder.isFastPool) { if (!builder.isFastPool) {
if (builder.queueType != null) { if (builder.queueType != null) {
builder.workQueue = QueueTypeEnum.createBlockingQueue(builder.queueType.type, builder.capacity); builder.workQueue = QueueTypeEnum.createBlockingQueue(builder.queueType.type, builder.capacity);
} }
initParam.setWorkQueue(builder.workQueue); initParam.setWorkQueue(builder.workQueue);
} }
return initParam; return initParam;
} }
} }

@ -27,7 +27,7 @@ import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle; import org.springframework.boot.ansi.AnsiStyle;
/** /**
* Dynamic thread pool print banner. * Dynamic thread-pool print banner.
* *
* @author chen.ma * @author chen.ma
* @date 2021/6/20 16:34 * @date 2021/6/20 16:34

@ -20,7 +20,7 @@ package cn.hippo4j.core.spi;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
/** /**
* Custom blockingQueue. * Custom blocking-queue.
* *
* @author chen.ma * @author chen.ma
* @date 2021/7/11 00:51 * @date 2021/7/11 00:51

@ -20,7 +20,7 @@ package cn.hippo4j.core.spi;
import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.RejectedExecutionHandler;
/** /**
* Custom rejectedExecution handler. * Custom rejected execution handler.
* *
* @author chen.ma * @author chen.ma
* @date 2021/7/10 23:51 * @date 2021/7/10 23:51

@ -22,7 +22,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* Dynamic threadPool service loader. * Dynamic thread-pool service loader.
* *
* @author chen.ma * @author chen.ma
* @date 2021/7/10 23:45 * @date 2021/7/10 23:45

@ -25,13 +25,6 @@ package cn.hippo4j.core.toolkit;
*/ */
public class CalculateUtil { public class CalculateUtil {
/**
* Divide.
*
* @param num1
* @param num2
* @return
*/
public static int divide(int num1, int num2) { public static int divide(int num1, int num2) {
return ((int) (Double.parseDouble(num1 + "") / Double.parseDouble(num2 + "") * 100)); return ((int) (Double.parseDouble(num1 + "") / Double.parseDouble(num2 + "") * 100));
} }

@ -22,7 +22,7 @@ import org.slf4j.MDC;
import static cn.hippo4j.common.constant.Constants.EXECUTE_TIMEOUT_TRACE; import static cn.hippo4j.common.constant.Constants.EXECUTE_TIMEOUT_TRACE;
/** /**
* MD util. * Trace context util.
* *
* @author chen.ma * @author chen.ma
* @date 2022/3/3 08:30 * @date 2022/3/3 08:30

@ -228,7 +228,5 @@ public class InetUtils implements Closeable {
public void setHostname(String hostname) { public void setHostname(String hostname) {
this.hostname = hostname; this.hostname = hostname;
} }
} }
} }

@ -121,5 +121,4 @@ public class InetUtilsProperties {
public void setPreferredNetworks(List<String> preferredNetworks) { public void setPreferredNetworks(List<String> preferredNetworks) {
this.preferredNetworks = preferredNetworks; this.preferredNetworks = preferredNetworks;
} }
} }

@ -61,5 +61,4 @@ public enum ConfigFileTypeEnum {
* @return * @return
*/ */
public abstract String type(); public abstract String type();
} }

@ -146,5 +146,4 @@ public class BootstrapCoreProperties implements BootstrapPropertiesInterface {
* Executors. * Executors.
*/ */
private List<ExecutorProperties> executors; private List<ExecutorProperties> executors;
} }

@ -50,7 +50,7 @@ import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
/** /**
* Dynamic thread pool auto configuration. * Dynamic thread-pool auto configuration.
* *
* @author chen.ma * @author chen.ma
* @date 2022/2/25 00:21 * @date 2022/2/25 00:21
@ -163,5 +163,4 @@ public class DynamicThreadPoolCoreAutoConfiguration {
public MetricMonitorHandler hippo4jMetricMonitorHandler(ThreadPoolRunStateHandler threadPoolRunStateHandler) { public MetricMonitorHandler hippo4jMetricMonitorHandler(ThreadPoolRunStateHandler threadPoolRunStateHandler) {
return new MetricMonitorHandler(threadPoolRunStateHandler); return new MetricMonitorHandler(threadPoolRunStateHandler);
} }
} }

@ -93,5 +93,4 @@ public class ExecutorProperties {
public Map<String, String> receives() { public Map<String, String> receives() {
return Objects.isNull(this.notify) || this.notify.getReceives() == null ? Maps.newHashMap() : this.notify.getReceives(); return Objects.isNull(this.notify) || this.notify.getReceives() == null ? Maps.newHashMap() : this.notify.getReceives();
} }
} }

@ -49,5 +49,4 @@ public class NotifyPlatformProperties {
* Secret. * Secret.
*/ */
private String secret; private String secret;
} }

@ -42,5 +42,4 @@ public class WebThreadPoolProperties {
* Keep alive time * Keep alive time
*/ */
private Integer keepAliveTime; private Integer keepAliveTime;
} }

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save