Code optimization and logic refactoring

pull/909/head
chen.ma 3 years ago
parent 645a696383
commit dc9c36691e

@ -72,7 +72,7 @@ public abstract class AbstractRobotSendMessageHandler implements SendMessageHand
} else {
replaceTxt = "";
}
alarmContentTxt = StringUtil.replace(alarmContentTxt, "${timout-content}", replaceTxt);
alarmContentTxt = StringUtil.replace(alarmContentTxt, "${timeout-content}", replaceTxt);
String text = String.format(
alarmContentTxt,
alarmNotifyRequest.getActive(),

@ -18,7 +18,6 @@
package cn.hippo4j.message.service;
import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.toolkit.IdUtil;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.message.dto.AlarmControlDTO;
import com.github.benmanes.caffeine.cache.Cache;
@ -58,8 +57,7 @@ public class AlarmControlHandler {
try {
pkId = cache.getIfPresent(alarmControl.getTypeEnum().name());
if (StringUtil.isBlank(pkId)) {
// Val meaningless.
cache.put(alarmControl.getTypeEnum().name(), IdUtil.simpleUUID());
cache.put(alarmControl.getTypeEnum().name(), "-");
return true;
}
} finally {

@ -34,7 +34,7 @@
---
${timout-content}
${timeout-content}
<font color=#708090 size=2>拒绝策略:%s</font>

@ -14,7 +14,7 @@
> 队列元素个数:%s
> 队列剩余个数:%s
> 拒绝策略:%s
> 拒绝策略执行次数:<font color='#FF0000'>%s</font> ${timout-content}
> 拒绝策略执行次数:<font color='#FF0000'>%s</font> ${timeout-content}
> OWNER<@%s>
> 提示:%d 分钟内此线程池不会重复告警(可配置)

@ -42,9 +42,6 @@ public abstract class AbstractDynamicThreadPoolMonitor implements DynamicThreadP
@Override
public void collect() {
List<String> listDynamicThreadPoolId = GlobalThreadPoolManage.listThreadPoolId();
for (String each : listDynamicThreadPoolId) {
ThreadPoolRunStateInfo poolRunState = threadPoolRunStateHandler.getPoolRunState(each);
execute(poolRunState);
}
listDynamicThreadPoolId.forEach(each -> execute(threadPoolRunStateHandler.getPoolRunState(each)));
}
}

@ -21,5 +21,4 @@ package cn.hippo4j.monitor.base;
* Adapter thread-pool monitor.
*/
public interface AdapterThreadPoolMonitor extends ThreadPoolMonitor {
}

@ -21,5 +21,4 @@ package cn.hippo4j.monitor.base;
* Dynamic thread-pool monitor.
*/
public interface DynamicThreadPoolMonitor extends ThreadPoolMonitor {
}

@ -21,5 +21,4 @@ package cn.hippo4j.monitor.base;
* Web thread-pool monitor.
*/
public interface WebThreadPoolMonitor extends ThreadPoolMonitor {
}

@ -46,10 +46,10 @@ public class AdapterThreadPoolMicrometerMonitorHandler extends AbstractAdapterTh
@Override
protected void execute(ThreadPoolAdapterState threadPoolAdapterState) {
ThreadPoolAdapterState stateInfo = RUN_STATE_CACHE.get(threadPoolAdapterState.getThreadPoolKey());
if (stateInfo == null) {
RUN_STATE_CACHE.put(threadPoolAdapterState.getThreadPoolKey(), threadPoolAdapterState);
} else {
if (stateInfo != null) {
BeanUtil.convert(threadPoolAdapterState, stateInfo);
} else {
RUN_STATE_CACHE.put(threadPoolAdapterState.getThreadPoolKey(), threadPoolAdapterState);
}
Environment environment = ApplicationContextHolder.getInstance().getEnvironment();
String applicationName = environment.getProperty("spring.application.name", "application");

@ -46,10 +46,10 @@ public class DynamicThreadPoolMicrometerMonitorHandler extends AbstractDynamicTh
@Override
protected void execute(ThreadPoolRunStateInfo poolRunStateInfo) {
ThreadPoolRunStateInfo stateInfo = RUN_STATE_CACHE.get(poolRunStateInfo.getTpId());
if (stateInfo == null) {
RUN_STATE_CACHE.put(poolRunStateInfo.getTpId(), poolRunStateInfo);
} else {
if (stateInfo != null) {
BeanUtil.convert(poolRunStateInfo, stateInfo);
} else {
RUN_STATE_CACHE.put(poolRunStateInfo.getTpId(), poolRunStateInfo);
}
Environment environment = ApplicationContextHolder.getInstance().getEnvironment();
String applicationName = environment.getProperty("spring.application.name", "application");

@ -46,10 +46,10 @@ public class WebThreadPoolMicrometerMonitorHandler extends AbstractWebThreadPool
Environment environment = ApplicationContextHolder.getInstance().getEnvironment();
String applicationName = environment.getProperty("spring.application.name", "application");
ThreadPoolRunStateInfo stateInfo = RUN_STATE_CACHE.get(applicationName);
if (stateInfo == null) {
RUN_STATE_CACHE.put(applicationName, webThreadPoolRunStateInfo);
} else {
if (stateInfo != null) {
BeanUtil.convert(webThreadPoolRunStateInfo, stateInfo);
} else {
RUN_STATE_CACHE.put(applicationName, webThreadPoolRunStateInfo);
}
Iterable<Tag> tags = CollectionUtil.newArrayList(Tag.of(APPLICATION_NAME_TAG, applicationName));
Metrics.gauge(metricName("current.load"), tags, webThreadPoolRunStateInfo, ThreadPoolRunStateInfo::getSimpleCurrentLoad);

@ -23,7 +23,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
* Filter config.
*/
@Configuration
public class FilterConfig {

@ -68,14 +68,12 @@ public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
chain.doFilter(request, response);
return;
}
// If there is no Authorization information in the request header, it will be released directly.
String tokenHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
chain.doFilter(request, response);
return;
}
// If there is a Token in the request header, it is parsed and the authentication information is set.
try {
SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));

@ -41,15 +41,30 @@ import static cn.hippo4j.common.constant.Constants.AUTHORITIES_KEY;
@Component
public class JwtTokenManager {
/**
* Create token.
*
* @param userName user-name
* @return new token
*/
public String createToken(String userName) {
long now = System.currentTimeMillis();
Date validity;
validity = new Date(now + TOKEN_VALIDITY_IN_SECONDS * 1000L);
Claims claims = Jwts.claims().setSubject(userName);
return Jwts.builder().setClaims(claims).setExpiration(validity)
.signWith(SignatureAlgorithm.HS512, SECRET).compact();
String token = Jwts.builder()
.setClaims(claims)
.setExpiration(validity)
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
return token;
}
/**
* Validate token.
*
* @param token token
*/
public void validateToken(String token) {
Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
}

@ -22,7 +22,6 @@ import cn.hippo4j.auth.model.UserInfo;
import cn.hippo4j.auth.model.biz.user.UserQueryPageReqDTO;
import cn.hippo4j.auth.model.biz.user.UserReqDTO;
import cn.hippo4j.auth.model.biz.user.UserRespDTO;
import cn.hippo4j.auth.service.RoleService;
import cn.hippo4j.auth.service.UserService;
import cn.hippo4j.common.toolkit.BeanUtil;
import cn.hippo4j.common.toolkit.StringUtil;
@ -49,8 +48,6 @@ public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
private final RoleService roleService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Override

@ -36,9 +36,11 @@ import static cn.hippo4j.common.constant.Constants.MAP_INITIAL_CAPACITY;
public class JwtTokenUtil {
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
public static final String SECRET = "SecretKey039245678901232039487623456783092349288901402967890140939827";
public static final String ISS = "admin";
/**

@ -32,13 +32,17 @@ public class ReturnT<T> implements Serializable {
public static final long serialVersionUID = 42L;
public static final int SUCCESS_CODE = 200;
public static final int FAIL_CODE = 500;
public static final ReturnT<String> SUCCESS = new ReturnT<>(null);
public static final ReturnT<String> FAIL = new ReturnT<>(FAIL_CODE, null);
private int code;
private String msg;
private T content;
public ReturnT(int code, String msg) {

@ -1,44 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hippo4j.config.event;
import org.springframework.util.StringUtils;
/**
* Config data change event.
*/
public class ConfigDataChangeEvent extends AbstractEvent {
public final String tenantId;
public final String itemId;
public final String tpId;
public final long lastModifiedTs;
public ConfigDataChangeEvent(String tenantId, String itemId, String tpId, Long gmtModified) {
if (StringUtils.isEmpty(tenantId) || StringUtils.isEmpty(itemId) || StringUtils.isEmpty(tpId)) {
throw new IllegalArgumentException("DataId is null or group is null");
}
this.tenantId = tenantId;
this.itemId = itemId;
this.tpId = tpId;
this.lastModifiedTs = gmtModified;
}
}

@ -27,14 +27,14 @@ public abstract class AbstractMonitorDataExecuteStrategy<T extends Message> {
/**
* Mark.
*
* @return
* @return mark
*/
public abstract String mark();
/**
* Execute.
*
* @param message
* @param message message
*/
public abstract void execute(T message);
}

@ -33,7 +33,7 @@ import java.util.Map;
public class QueryMonitorExecuteChoose implements CommandLineRunner {
/**
* Storage monitoring data execution container.
* Storage monitoring data execution container
*/
private Map<String, AbstractMonitorDataExecuteStrategy> monitorDataExecuteStrategyChooseMap = new HashMap<>();

@ -63,7 +63,6 @@ public class DefaultPublisher extends Thread implements EventPublisher {
@Override
public synchronized void start() {
if (!initialized) {
// start just called once
super.start();
if (queueMaxSize == -1) {
queueMaxSize = NotifyCenter.ringBufferSize;
@ -80,7 +79,7 @@ public class DefaultPublisher extends Thread implements EventPublisher {
private void openEventHandler() {
try {
int waitTimes = 60;
for (;;) {
for (; ; ) {
if (shutdown || hasSubscriber() || waitTimes <= 0) {
break;
}
@ -91,7 +90,7 @@ public class DefaultPublisher extends Thread implements EventPublisher {
}
waitTimes--;
}
for (;;) {
for (; ; ) {
if (shutdown) {
break;
}
@ -100,7 +99,7 @@ public class DefaultPublisher extends Thread implements EventPublisher {
UPDATER.compareAndSet(this, lastEventSequence, Math.max(lastEventSequence, event.sequence()));
}
} catch (Throwable ex) {
log.error("Event listener exception: {}", ex);
log.error("Event listener exception.", ex);
}
}
@ -123,9 +122,7 @@ public class DefaultPublisher extends Thread implements EventPublisher {
@Override
public void notifySubscriber(AbstractSubscriber subscriber, AbstractEvent event) {
final Runnable job = () -> subscriber.onEvent(event);
final Executor executor = subscriber.executor();
if (executor != null) {
executor.execute(job);
} else {

@ -28,31 +28,31 @@ public interface EventPublisher {
/**
* Init.
*
* @param type
* @param bufferSize
* @param type type
* @param bufferSize buffer size
*/
void init(Class<? extends AbstractEvent> type, int bufferSize);
/**
* Add subscriber.
*
* @param subscriber
* @param subscriber subscriber
*/
void addSubscriber(AbstractSubscriber subscriber);
/**
* Publish.
*
* @param event
* @return
* @param event event
* @return publish result
*/
boolean publish(AbstractEvent event);
/**
* Notify subscriber.
*
* @param subscriber
* @param event
* @param subscriber subscriber
* @param event event
*/
void notifySubscriber(AbstractSubscriber subscriber, AbstractEvent event);
}

@ -43,11 +43,9 @@ public class NotifyCenter {
private DefaultSharePublisher sharePublisher;
private static Class<? extends EventPublisher> clazz = null;
private static EventPublisher eventPublisher = new DefaultPublisher();
private static BiFunction<Class<? extends AbstractEvent>, Integer, EventPublisher> publisherFactory = null;
private static BiFunction<Class<? extends AbstractEvent>, Integer, EventPublisher> publisherFactory;
private final Map<String, EventPublisher> publisherMap = new ConcurrentHashMap(16);

@ -40,6 +40,11 @@ public abstract class AbstractSubscriber<T extends AbstractEvent> {
*/
public abstract Class<? extends AbstractEvent> subscribeType();
/**
* Executor.
*
* @return executor
*/
public Executor executor() {
return null;
}

@ -28,7 +28,7 @@ public class ConfigChangePublisher {
/**
* Notify configChange.
*
* @param event
* @param event event
*/
public static void notifyConfigChange(LocalDataChangeEvent event) {
NotifyCenter.publishEvent(event);

@ -68,13 +68,9 @@ public class LongPollingService {
@Override
public void onEvent(AbstractEvent event) {
if (isFixedPolling()) {
// Ignore.
} else {
if (event instanceof LocalDataChangeEvent) {
LocalDataChangeEvent evt = (LocalDataChangeEvent) event;
ConfigExecutor.executeLongPolling(new DataChangeTask(evt.identify, evt.groupKey));
}
if (!isFixedPolling() && event instanceof LocalDataChangeEvent) {
LocalDataChangeEvent evt = (LocalDataChangeEvent) event;
ConfigExecutor.executeLongPolling(new DataChangeTask(evt.identify, evt.groupKey));
}
}
@ -109,7 +105,7 @@ public class LongPollingService {
@Override
public void run() {
try {
for (Iterator<ClientLongPolling> iter = allSubs.iterator(); iter.hasNext();) {
for (Iterator<ClientLongPolling> iter = allSubs.iterator(); iter.hasNext(); ) {
ClientLongPolling clientSub = iter.next();
String identity = groupKey + GROUP_KEY_DELIMITER + identify;
List<String> parseMapForFilter = CollectionUtil.newArrayList(identity);
@ -300,11 +296,11 @@ public class LongPollingService {
/**
* Is support long polling.
*
* @param req
* @param request
* @return
*/
public static boolean isSupportLongPolling(HttpServletRequest req) {
return null != req.getHeader(LONG_POLLING_HEADER);
public static boolean isSupportLongPolling(HttpServletRequest request) {
return request.getHeader(LONG_POLLING_HEADER) != null;
}
/**

@ -33,7 +33,7 @@ import java.util.Map;
public class ConfigModificationVerifyServiceChoose implements CommandLineRunner {
/**
* Storage config change verify service container.
* Storage config change verify service container
*/
private Map<Integer, ConfigModificationVerifyService> configChangeVerifyServiceChooseMap = new HashMap<>();
@ -44,8 +44,7 @@ public class ConfigModificationVerifyServiceChoose implements CommandLineRunner
* @return
*/
public ConfigModificationVerifyService choose(Integer type) {
ConfigModificationVerifyService verifyService = configChangeVerifyServiceChooseMap.get(type);
return verifyService;
return configChangeVerifyServiceChooseMap.get(type);
}
@Override

@ -17,32 +17,19 @@
package cn.hippo4j.discovery.core;
import lombok.Getter;
/**
* Lease.
*/
public class Lease<T> {
enum Action {
/**
* REGISTER
*/
REGISTER,
/**
* CANCEL
*/
CANCEL,
/**
* RENEW
*/
RENEW
}
private T holder;
@Getter
private long evictionTimestamp;
@Getter
private long registrationTimestamp;
private long serviceUpTimestamp;
@ -50,6 +37,7 @@ public class Lease<T> {
/**
* Make it volatile so that the expiration task would see this quicker
*/
@Getter
private volatile long lastUpdateTimestamp;
private long duration;
@ -91,18 +79,6 @@ public class Lease<T> {
return (evictionTimestamp > 0 || System.currentTimeMillis() > (lastUpdateTimestamp + additionalLeaseMs));
}
public long getRegistrationTimestamp() {
return registrationTimestamp;
}
public long getLastRenewalTimestamp() {
return lastUpdateTimestamp;
}
public long getEvictionTimestamp() {
return evictionTimestamp;
}
public long getServiceUpTimestamp() {
return serviceUpTimestamp;
}

Loading…
Cancel
Save