optimization1

This commit is contained in:
hongqiaowei
2022-07-09 11:07:15 +08:00
parent 825959e5d6
commit 7799360a80
6 changed files with 234 additions and 66 deletions

View File

@@ -56,6 +56,13 @@
<artifactId>fizz-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator-i18n-support</artifactId>
<version>1.0.39_5</version>
</dependency>
<!-- import fizz-input-mysql -->
<!-- <dependency>
<groupId>com.fizzgate</groupId>
@@ -111,6 +118,13 @@
</profile>-->
</profiles>
<repositories>
<repository>
<id>repo</id>
<url>file://${project.basedir}/../repo</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
@@ -118,6 +132,12 @@
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
<excludes>
<exclude>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator-i18n-support</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>

View File

@@ -17,7 +17,12 @@
package we.util;
import java.time.*;
import we.util.Consts.DP;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
@@ -26,8 +31,6 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import we.util.Consts.DP;
/**
* @author hongqiaowei
*/
@@ -165,6 +168,27 @@ public abstract class DateTimeUtils {
return localDate1.isEqual(localDate2);
}
public static long get10sTimeWinStart(int n) {
LocalDateTime now = LocalDateTime.now().with(ChronoField.MILLI_OF_SECOND, 0);
int sec = now.getSecond();
long interval;
if (sec > 49) {
interval = sec - 50;
} else if (sec > 39) {
interval = sec - 40;
} else if (sec > 29) {
interval = sec - 30;
} else if (sec > 19) {
interval = sec - 20;
} else if (sec > 9) {
interval = sec - 10;
} else {
interval = sec;
}
long millis = toMillis(now);
return millis - interval * 1000 - (n - 1) * 10L * 1000;
}
/*
void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2021 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.plugin.stat;
import we.util.JacksonUtils;
/**
* @author hongqiaowei
*/
public class AccessStat {
public String service;
public String apiMethod;
public String apiPath;
public long start;
public int reqs = 0;
public long reqTime;
@Override
public String toString() {
return JacksonUtils.writeValueAsString(this);
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright (C) 2021 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.plugin.stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import we.config.AggregateRedisConfig;
import we.config.SchedConfig;
import we.util.Consts;
import we.util.DateTimeUtils;
import we.util.StringUtils;
import javax.annotation.Resource;
import java.util.Map;
/**
* @author hongqiaowei
*/
@Configuration
public class AccessStatSchedConfig extends SchedConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AccessStatSchedConfig.class);
private static final Logger STAT_LOGGER = LoggerFactory.getLogger("stat");
@Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE)
private ReactiveStringRedisTemplate rt;
@Resource
private StatPluginFilterProperties statPluginFilterProperties;
@Resource
private StatPluginFilter statPluginFilter;
@Scheduled(cron = "${fizz-access-stat-sched.cron:2/10 * * * * ?}")
public void sched() {
long prevTimeWinStart = DateTimeUtils.get10sTimeWinStart(2);
Map<String, AccessStat> accessStatMap = statPluginFilter.getAccessStat(prevTimeWinStart);
if (accessStatMap.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("no access stat in {} window", DateTimeUtils.convert(prevTimeWinStart, Consts.DP.DP19));
}
} else {
accessStatMap.forEach(
(smp, accessStat) -> {
String msg = accessStat.toString();
String topic = statPluginFilterProperties.getFizzAccessStatTopic();
if (StringUtils.isBlank(topic)) {
String channel = statPluginFilterProperties.getFizzAccessStatChannel();
rt.convertAndSend(channel, msg).subscribe();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("send access stat {} which belong to {} window to channel {}", msg, DateTimeUtils.convert(accessStat.start, Consts.DP.DP19), channel);
}
} else {
STAT_LOGGER.info(msg);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("send access stat {} which belong to {} window to topic", msg, DateTimeUtils.convert(accessStat.start, Consts.DP.DP19));
}
}
}
);
}
}
}

View File

@@ -17,21 +17,20 @@
package we.plugin.stat;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import we.config.AggregateRedisConfig;
import we.plugin.PluginFilter;
import we.plugin.auth.GatewayGroupService;
import we.util.Consts;
import we.util.DateTimeUtils;
import we.util.ThreadContext;
import we.util.WebUtils;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
@@ -42,82 +41,84 @@ import java.util.Map;
@Component(StatPluginFilter.STAT_PLUGIN_FILTER)
public class StatPluginFilter extends PluginFilter {
private static final Logger log = LoggerFactory.getLogger("stat");
private static final Logger LOGGER = LoggerFactory.getLogger(StatPluginFilter.class);
public static final String STAT_PLUGIN_FILTER = "statPlugin";
private static final String ip = "\"ip\":";
private static final String gatewayGroup = "\"gatewayGroup\":";
private static final String service = "\"service\":";
private static final String appid = "\"appid\":";
private static final String apiMethod = "\"apiMethod\":";
private static final String apiPath = "\"apiPath\":";
private static final String reqTime = "\"reqTime\":";
@Resource
private StatPluginFilterProperties statPluginFilterProperties;
@Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE)
private ReactiveStringRedisTemplate rt;
@Resource
private GatewayGroupService gatewayGroupService;
private Map<Long/*thread id*/,
Map/*LinkedHashMap*/<Long/*time win start*/,
Map<String/*service+apiMethod+apiPath*/, AccessStat>
>
>
threadTimeWinAccessStatMap = new HashMap<>();
@Override
public Mono<Void> doFilter(ServerWebExchange exchange, Map<String, Object> config, String fixedConfig) {
if (statPluginFilterProperties.isStatOpen()) {
StringBuilder b = ThreadContext.getStringBuilder();
b.append(Consts.S.LEFT_BRACE);
b.append(ip); toJsonStringValue(b, WebUtils.getOriginIp(exchange)); b.append(Consts.S.COMMA);
b.append(gatewayGroup); toJsonStringValue(b, currentGatewayGroups()); b.append(Consts.S.COMMA);
b.append(service); toJsonStringValue(b, WebUtils.getClientService(exchange)); b.append(Consts.S.COMMA);
long tid = Thread.currentThread().getId();
Map<Long, Map<String, AccessStat>> timeWinAccessStatMap = threadTimeWinAccessStatMap.get(tid);
if (timeWinAccessStatMap == null) {
timeWinAccessStatMap = new LinkedHashMap<Long, Map<String, AccessStat>>(4, 1) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > 2;
}
};
threadTimeWinAccessStatMap.put(tid, timeWinAccessStatMap);
}
String appId = WebUtils.getAppId(exchange);
if (appId != null) {
b.append(appid); toJsonStringValue(b, appId); b.append(Consts.S.COMMA);
}
long currentTimeWinStart = DateTimeUtils.get10sTimeWinStart(1);
Map<String, AccessStat> accessStatMap = timeWinAccessStatMap.computeIfAbsent(currentTimeWinStart, k -> new HashMap<>(128));
b.append(apiMethod); toJsonStringValue(b, exchange.getRequest().getMethodValue()); b.append(Consts.S.COMMA);
b.append(apiPath); toJsonStringValue(b, WebUtils.getClientReqPath(exchange)); b.append(Consts.S.COMMA);
b.append(reqTime) .append(System.currentTimeMillis());
b.append(Consts.S.RIGHT_BRACE);
if (StringUtils.isBlank(statPluginFilterProperties.getFizzAccessStatTopic())) {
rt.convertAndSend(statPluginFilterProperties.getFizzAccessStatChannel(), b.toString()).subscribe();
} else {
// log.warn(b.toString(), LogService.HANDLE_STGY, LogService.toKF(statPluginFilterProperties.getFizzAccessStatTopic())); // for internal use
log.info(b.toString());
String service = WebUtils.getClientService(exchange);
String method = exchange.getRequest().getMethodValue();
String path = WebUtils.getClientReqPath(exchange);
String key = ThreadContext.getStringBuilder().append(service).append(method).append(path).toString();
AccessStat accessStat = accessStatMap.get(key);
if (accessStat == null) {
accessStat = new AccessStat();
accessStat.service = service;
accessStat.apiMethod = method;
accessStat.apiPath = path;
accessStatMap.put(key, accessStat);
}
accessStat.reqTime = System.currentTimeMillis();
accessStat.reqs++;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("update access stat: {}, which request at {}", accessStat, DateTimeUtils.convert(accessStat.reqTime, Consts.DP.DP19));
}
}
return WebUtils.transmitSuccessFilterResultAndEmptyMono(exchange, STAT_PLUGIN_FILTER, null);
}
private String currentGatewayGroups() {
int sz = gatewayGroupService.currentGatewayGroupSet.size();
if (sz == 1) {
return gatewayGroupService.currentGatewayGroupSet.iterator().next();
}
StringBuilder b = ThreadContext.getStringBuilder(ThreadContext.sb0);
byte i = 0;
for (String g : gatewayGroupService.currentGatewayGroupSet) {
b.append(g);
i++;
if (i < sz) {
b.append(Consts.S.COMMA);
}
}
return b.toString();
}
private static void toJsonStringValue(StringBuilder b, String value) {
b.append(Consts.S.DOUBLE_QUOTE).append(value).append(Consts.S.DOUBLE_QUOTE);
public Map<String, AccessStat> getAccessStat(long timeWinStart) {
Map<String, AccessStat> result = ThreadContext.getHashMap();
threadTimeWinAccessStatMap.forEach(
(t, timeWinAccessStatMap) -> {
Map<String, AccessStat> accessStatMap = timeWinAccessStatMap.get(timeWinStart);
if (accessStatMap != null) {
accessStatMap.forEach(
(smp, accessStat) -> {
AccessStat as = result.get(smp);
if (as == null) {
accessStat.start = timeWinStart;
result.put(smp, accessStat);
} else {
as.reqs = as.reqs + accessStat.reqs;
if (accessStat.reqTime > as.reqTime) {
as.reqTime = accessStat.reqTime;
}
}
}
);
}
}
);
return result;
}
}

View File

@@ -37,7 +37,7 @@ public class StatPluginFilterProperties {
@Value("${stat.open:false}")
private boolean statOpen = false;
@Value("${stat.channel:fizz_access_stat}")
@Value("${stat.channel:fizz_access_stat_new}")
private String fizzAccessStatChannel;
@Value("${stat.topic:}")