Commit c2d96cf9 by 黄超华

init

0 parents
Showing 70 changed files with 4390 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-common-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<description>Microservice Scaffolding Api Base on Spring Cloud</description>
<artifactId>platform-auth-api</artifactId>
<dependencies>
<!-- mybatis -->
<!-- <dependency>-->
<!-- <groupId>com.glsx</groupId>-->
<!-- <artifactId>rest-admin-mybatis</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-jwt</artifactId>
</dependency>
<!-- feign -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.admin.config;
import cn.com.glsx.admin.model.GatewayService;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author huangch
* @version V1.0
* @Title: ApiGatewayConsumerConfig
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/6 10:36
*/
@ConfigurationProperties(prefix = "gateway")
@Component
public class ApiGatewayServiceConfig {
private Map<String, GatewayService> services;
private Boolean signSwitch;
public void setSignSwitch(Boolean signSwitch) {
this.signSwitch = signSwitch;
}
public void setServices(Map<String, GatewayService> services) {
Map<String, GatewayService> newMap = new ConcurrentHashMap<>();
for(Map.Entry<String, GatewayService> entry : services.entrySet()){
GatewayService gatewayService = entry.getValue();
gatewayService.setName(entry.getKey());
newMap.put(gatewayService.getAppKey(), gatewayService);
}
this.services = newMap;
}
public GatewayService getServiceByAppKey(String appKey){
return this.services .get(appKey);
}
}
package cn.com.glsx.admin.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author huangch
* @version V1.0
* @Title: Consumer
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/6 10:40
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GatewayService {
/**
* 调用方英文名称
*/
private String name;
/**
* 调用方中文名称
*/
private String remark;
/**
* appKey
*/
private String appKey;
/**
* secret:秘钥
*/
private String secret;
/**
* 是否对调用方开启IP鉴权
*/
private Boolean ipAuth;
/**
* 调用方IP白名单
*/
private String whiteIps;
/**
* 是否校验调用方的签名
*/
private Boolean checkSign;
/**
* 是否校验调用方的JWT
*/
private Boolean jwtAuth;
/**
* 签名的有效时间,默认24小时
*/
private Long jwtTtl = 24 * 60 * 60 * 1000L;
/**
* 生效时间偏移量
*/
private Integer jwtIssueAtOffset;
}
package cn.com.glsx.admin.utils;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import cn.com.glsx.admin.model.GatewayService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class GatewayJwtUtils implements InitializingBean {
private static final Logger log = LoggerFactory.getLogger(GatewayJwtUtils.class);
private static final String PAYLOAD_MAP = "payloadMap";
public final String JWT_SESSION_PREFIX = "JWT-SESSION-";
public final String CLAZZ = "clazz";
public final String BEARER = "Bearer ";
@Resource
private StringRedisTemplate stringRedisTemplate;
public GatewayJwtUtils() {
}
@Override
public void afterPropertiesSet() throws Exception {
}
public static void main(String[] args) {
// GatewayService gatewayService = GatewayService.builder().name("scrm-shopmall")
// .remark("scrm商城")
// .appKey("48e5e13229b82c1b4e6e8c96151f0637")
// .secret("c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b")
// .ipAuth(true)
// .whiteIps("192.168.1.140,192.168.0.1")
// .checkSign(true)
// .jwtAuth(true)
// .jwtTtl(86400000L)
// .jwtIssueAtOffset(60000)
// .build();
// Map<String, Object> userMap = new ConcurrentHashMap<>();
// userMap.put("name", gatewayService.getName());
// GatewayJwtUtils jwtUtils = new GatewayJwtUtils();
// String token = jwtUtils.createToken(userMap, gatewayService);
// DecodedJWT decode = jwtUtils.decode(token);
// System.out.println(decode.getClaim("name"));
}
public String genSecretKey(Instant instant) {
return String.valueOf(instant.getEpochSecond());
}
public static String createToken(Map<String, Object> userMap, GatewayService gatewayService) {
String token = create(userMap, Instant.now(), gatewayService);
log.debug("create id {} token [" + token + "]", gatewayService.getName());
return token;
}
public String createCachedToken(Map<String, Object> userMap, GatewayService gatewayService) {
String token = this.create(userMap, Instant.now(), gatewayService);
this.stringRedisTemplate.opsForValue().set(gatewayService.getName(), token, gatewayService.getJwtTtl(), TimeUnit.MILLISECONDS);
log.debug("create id {} token [" + token + "]", gatewayService.getName());
return token;
}
private static String create(Map<String, Object> claims, Instant issueAt, GatewayService gatewayService) {
Algorithm algorithm = Algorithm.HMAC256(gatewayService.getSecret());
Instant exp = issueAt.plusSeconds(gatewayService.getJwtTtl());
Map<String, Object> newClaims = new HashMap();
Iterator var9 = claims.entrySet().iterator();
while(var9.hasNext()) {
Entry<String, Object> entry = (Entry)var9.next();
String key = (String)entry.getKey();
Object value = entry.getValue();
if (!"class".equals(key) && !Objects.isNull(value)) {
newClaims.put(key, value);
}
}
JWTCreator.Builder builder = JWT.create().withJWTId(gatewayService.getName()).withClaim("iat", Date.from(issueAt.plusSeconds(gatewayService.getJwtIssueAtOffset() == null ? 0L : (long)(-gatewayService.getJwtIssueAtOffset())))).withClaim("exp", Date.from(exp)).withClaim("payloadMap", newClaims);
builder.withSubject(gatewayService.getName()).withClaim("name", gatewayService.getName());
String token = builder.sign(algorithm);
log.trace("create token [" + token + "]; iat: " + Date.from(exp) + " exp: " + Date.from(exp));
return token;
}
public DecodedJWT decode(String token) {
if (token.startsWith(BEARER)) {
token = token.replace(BEARER, "");
}
return com.auth0.jwt.JWT.decode(token);
}
public DecodedJWT verify(String token, GatewayService gatewayService) {
return this.verify(gatewayService.getSecret(), token);
}
public DecodedJWT verify(String secretKey, String token) {
if (token.startsWith(BEARER)) {
token = token.replace(BEARER, "");
}
Algorithm algorithm = Algorithm.HMAC256(secretKey);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = null;
try {
jwt = verifier.verify(token);
} catch (JWTVerificationException var7) {
log.error(var7.getMessage());
} catch (Exception var8) {
var8.printStackTrace();
log.error(var8.getMessage());
}
return jwt;
}
public Map<String, Object> parseClaim(String token) {
return this.decode(token).getClaim("payloadMap").asMap();
}
public Class getJwtUserClass(String token) throws ClassNotFoundException {
String jwtUserClazz = (String)this.parseClaim(token).get("clazz");
log.debug("token jwt user clazz [" + jwtUserClazz + "]");
Class clazz = Class.forName(jwtUserClazz);
return clazz;
}
public boolean verifyToken(String token, GatewayService gatewayService) {
log.debug("verify token [" + token + "]");
try {
this.verify(token, gatewayService);
return true;
} catch (JWTVerificationException var3) {
log.error(var3.getMessage());
} catch (Exception var4) {
var4.printStackTrace();
log.error(var4.getMessage());
}
return false;
}
public boolean verifyCachedToken(String token, GatewayService gatewayService) {
if (StringUtils.isEmpty(token)) {
return false;
} else {
if (token.startsWith(BEARER)) {
token = token.replace(BEARER, "");
}
try {
DecodedJWT decodedJWT = this.verify(token, gatewayService);
String redisToken = (String)this.stringRedisTemplate.opsForValue().get(decodedJWT.getId());
if (!token.equals(redisToken)) {
return false;
}
this.stringRedisTemplate.opsForValue().set(decodedJWT.getId(), redisToken, gatewayService.getJwtTtl(), TimeUnit.SECONDS);
return true;
} catch (TokenExpiredException var4) {
log.error(var4.getMessage());
} catch (Exception var5) {
var5.printStackTrace();
log.error(var5.getMessage());
}
return false;
}
}
public boolean isTokenOutExpiresAt(DecodedJWT jwtToken, Instant instant) {
Instant exp = jwtToken.getExpiresAt().toInstant();
return instant.compareTo(exp) >= 0;
}
public String refreshCachedToken(DecodedJWT jwtToken, GatewayService gatewayService) {
String refreshToken = this.refreshToken(jwtToken, gatewayService);
this.stringRedisTemplate.opsForValue().set(gatewayService.getName(), refreshToken, gatewayService.getJwtTtl(), TimeUnit.SECONDS);
return refreshToken;
}
public String refreshToken(DecodedJWT jwtToken, GatewayService gatewayService) {
Instant now = Instant.now();
Instant exp = jwtToken.getExpiresAt().toInstant();
Algorithm algorithm = Algorithm.HMAC256(gatewayService.getSecret());
Instant newExp = exp.plusSeconds(gatewayService.getJwtTtl());
String token = JWT.create().withJWTId(jwtToken.getId()).withClaim("sub", jwtToken.getSubject()).withClaim("iat", Date.from(exp)).withClaim("exp", Date.from(newExp)).withClaim("payloadMap", jwtToken.getClaim("payloadMap").asMap()).sign(algorithm);
log.debug("create refresh token [" + token + "]; iat: " + Date.from(exp) + " exp: " + Date.from(newExp));
return token;
}
public void destroyToken(String token) {
this.decode(token);
}
public void destroyCachedToken(String token) {
DecodedJWT decodedJWT = this.decode(token);
this.stringRedisTemplate.delete(decodedJWT.getId());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-common-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<description>Microservice Scaffolding Project Base on Spring Cloud</description>
<artifactId>platform-auth</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- 运行环境上下文 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
</dependency>
<!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等 ,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-swagger3</artifactId>
</dependency>
<!-- local api -->
<dependency>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-auth-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import cn.com.glsx.admin.config.ApiGatewayServiceConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableConfigurationProperties({ApiGatewayServiceConfig.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.admin.modules.controller;
import cn.com.glsx.admin.config.ApiGatewayServiceConfig;
import cn.com.glsx.admin.model.GatewayService;
import cn.com.glsx.admin.utils.GatewayJwtUtils;
import com.glsx.plat.core.annotation.ResponseResultBody;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @author huangch
* @version V1.0
* @Title: AuthController
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/6 18:08
*/
@Slf4j
@RestController
@RequestMapping(value = "/auth")
@ResponseResultBody
public class AuthController {
@Autowired
private ApiGatewayServiceConfig apiGatewayServiceConfig;
@Autowired
private GatewayJwtUtils gatewayJwtUtils;
@GetMapping("/access-token/get")
public Object getAccessToken(HttpServletRequest request) {
String appKey = request.getHeader("appKey");
GatewayService gatewayService = apiGatewayServiceConfig.getServiceByAppKey(appKey);
if(gatewayService == null){
return R.error("appKey错误");
}
Map<String, Object> userMap = new HashMap<>();
userMap.put("name", gatewayService.getName());
String token = gatewayJwtUtils.createToken(userMap, gatewayService);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("token", token);
// resultMap.put("expiresAt", )
return R.ok(resultMap);
}
}
#项目名称
spring.application.name=platform-auth
server.servlet.context-path=/${spring.application.name}
server.port=8081
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8868
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
#配置分组(改成项目相关的)
spring.cloud.nacos.config.group=PLATFORM_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置环境
spring.profiles.active=dev
#配置格式
spring.cloud.nacos.config.file-extension=yaml
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=platform-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].data-id=platform-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[1].refresh=true
#鉴权公共配置
spring.cloud.nacos.config.shared-configs[2].data-id=plateform-auth-common-dev.yaml
spring.cloud.nacos.config.shared-configs[2].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[2].refresh=true
spring.main.allow-circular-references=true
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8820"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="rest-admin"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file \ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="rest-admin"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"addressCode": "3155",
"addressName": "南山区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "3638",
"addressName": "罗湖区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "3639",
"addressName": "福田区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "4773",
"addressName": "宝安区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "6675",
"addressName": "光明区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "6736",
"addressName": "坪山区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "6737",
"addressName": "大鹏新区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "40152",
"addressName": "龙岗区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "47387",
"addressName": "盐田区",
"parentAddressCode": "1607",
"addressLevel": 1003
},
{
"addressCode": "47388",
"addressName": "龙华区",
"parentAddressCode": "1607",
"addressLevel": 1003
}
],
"time": 1680751786484
}
\ No newline at end of file \ No newline at end of file
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"addressCode": "1601",
"addressName": "广州市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1607",
"addressName": "深圳市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1609",
"addressName": "珠海市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1611",
"addressName": "汕头市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1617",
"addressName": "韶关市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1627",
"addressName": "河源市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1634",
"addressName": "梅州市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1643",
"addressName": "惠州市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1650",
"addressName": "汕尾市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1655",
"addressName": "东莞市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1657",
"addressName": "中山市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1659",
"addressName": "江门市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1666",
"addressName": "佛山市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1672",
"addressName": "阳江市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1677",
"addressName": "湛江市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1684",
"addressName": "茂名市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1690",
"addressName": "肇庆市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1698",
"addressName": "云浮市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1704",
"addressName": "清远市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1705",
"addressName": "潮州市",
"parentAddressCode": "19",
"addressLevel": 1002
},
{
"addressCode": "1709",
"addressName": "揭阳市",
"parentAddressCode": "19",
"addressLevel": 1002
}
],
"time": 1680751048144
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": {
"pageNum": 1,
"pageSize": 100,
"totalCount": 13,
"totalPage": 1,
"goodsSkuList": [
{
"goodsCode": "281474976710658",
"goodsSkuCode": "281474976710659",
"goodsSkuName": "HUAWEI P30 屏内指纹 双景录像 全网通手机 6+128G 极光色 ",
"sellPrice": "320.30",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "2888888888888897",
"goodsSkuCode": "2888888888888898",
"goodsSkuName": "测试商品多规格-lzx 黑色 64G",
"sellPrice": "10.00",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "2888888888888897",
"goodsSkuCode": "2888888888888899",
"goodsSkuName": "测试商品多规格-lzx 星河银 128G",
"sellPrice": "100.00",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "2888888888888897",
"goodsSkuCode": "2888888888888900",
"goodsSkuName": "测试商品多规格-lzx 星河银 64G",
"sellPrice": "2.00",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "2888888889062492",
"goodsSkuCode": "2888888889071504",
"goodsSkuName": "新的手机 甜莓味 ",
"sellPrice": "114.14",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "2888888889076935",
"goodsSkuCode": "2888888889074811",
"goodsSkuName": "区域供应商商品测试 蓝色 ",
"sellPrice": "55.99",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "2888888889095873",
"goodsSkuCode": "2888888889093750",
"goodsSkuName": "手机mix4 珠光贝母",
"sellPrice": "2202.00",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "2888888889111384",
"goodsSkuCode": "2888888889109323",
"goodsSkuName": "vivo x80 pro+ 手机 丹青额 ",
"sellPrice": "100.00",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "844424930131972",
"goodsSkuCode": "844424930131972",
"goodsSkuName": "HUAWEI P30 屏内指纹 双景录像 全网通手机 8+256G 极光色 ",
"sellPrice": "320.30",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "844424930131976",
"goodsSkuCode": "844424930131976",
"goodsSkuName": "华为平板 M6 8.4英寸4GB+128GB WiFi(香槟金) 香槟色 ",
"sellPrice": "320.30",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "844424930131999",
"goodsSkuCode": "844424930132000",
"goodsSkuName": "HUAWEI Mate 30 5G 全网通 8GB+256GB 黑色 黑色 ",
"sellPrice": "320.30",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "844424930132000",
"goodsSkuCode": "844424930132001",
"goodsSkuName": "HUAWEI Mate 30 5G 全网通 8GB+256GB 银色 银色 ",
"sellPrice": "320.30",
"startQty": 1,
"shelvesStatus": 1001
},
{
"goodsCode": "844424930132082",
"goodsSkuCode": "844424930132093",
"goodsSkuName": "华为 HUAWEI Mate 30 6G+128GB 黑色 ",
"sellPrice": "320.30",
"startQty": 1,
"shelvesStatus": 1001
}
]
},
"time": 1680753148176
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": {
"tparOrderCode": "629811121721286656",
"parentOrderCode": "PO287826036798955546"
},
"time": 1680766445689
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": {
"tparOrderCode": "629808362271907840",
"parentOrderCode": "PO287823278662393883"
},
"time": 1680765788765
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"goodsCode": "281474976710658",
"goodsSkuCode": "281474976710659",
"goodsSkuName": "HUAWEI P30 屏内指纹 双景录像 全网通手机 6+128G 极光色 ",
"goodsSkuTitle": "手机",
"sellPrice": "320.30",
"marketPrice": "3688.00",
"shelvesStatus": 1001,
"startQty": 1,
"barCode": "0",
"isDeleted": 0,
"brandCode": "751",
"brandName": "华为",
"firstCategoryCode": "02",
"firstCategoryName": "手机",
"secondCategoryCode": "0201",
"secondCategoryName": "手机通讯",
"lastCategoryCode": "020102",
"lastCategoryName": "手机",
"returnGoodsRules": 1001,
"goodsCharacteristic": "麒麟980 超感光徕卡三摄 屏内指纹 双景录像",
"goodsUnit": "",
"modelNumber": "0",
"productPlace": "中国大陆",
"haveShelfLife": 1,
"shelfLife": "1",
"fragileGoods": 0,
"grossWeight": 165.00,
"grossWeightUnit": "kg",
"density": 0.00,
"extent": 149,
"width": 71,
"height": 7,
"taxCode": "",
"taxRate": 0.13,
"specList": [
{
"specName": "颜色",
"specValue": "极光色"
}
],
"descDetail": {
"goodsDescribe": "<figure class=\"image\"><img src=\"https://img.yunzhonghe.com/image/1571480617408CuekiGBeqi.jpg\"></figure><figure class=\"image\"><img src=\"https://img.yunzhonghe.com/image/1571480617043jqtDIWBYwt.jpg\"></figure><figure class=\"image\"><img src=\"https://img.yunzhonghe.com/image/1571480617041TBBotqyzBf.jpg\"></figure><figure class=\"image\"><img src=\"https://img.yunzhonghe.com/image/1571480617079sTQaJtpJAB.jpg\"></figure><figure class=\"image\"><img src=\"https://img.yunzhonghe.com/image/1571480617051uxibQYWVJY.jpg\"></figure>"
},
"attributeList": [
{
"attributeCode": "740",
"attributeName": "CPU型号",
"attributeValueCode": "844424930137042",
"attributeValueName": "Mali-G76 720MHz"
},
{
"attributeCode": "730",
"attributeName": "商品产地",
"attributeValueCode": "256",
"attributeValueName": "中国大陆"
},
{
"attributeCode": "731",
"attributeName": "系统",
"attributeValueCode": "259",
"attributeValueName": "Android"
}
]
}
],
"time": 1680753244085
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"goodsSkuCode": "281474976710659",
"imageList": [
{
"imgUrl": "https://img.yunzhonghe.com/image/1571480605913iYFGyDGVfN.jpg",
"imgMain": 1,
"imgSort": 0
}
]
}
],
"time": 1680753419483
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"goodsSkuCode": "281474976710659",
"saleLimitType": 1000,
"provinceIds": "",
"cityIds": "",
"areaIds": ""
}
],
"time": 1680753863578
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"goodsSkuCode": "281474976710659",
"sellPrice": "320.30",
"marketPrice": "3688.00"
}
],
"time": 1680753680855
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"goodsSkuCode": "281474976710659",
"stockStatus": 1001,
"stockNum": 99
}
],
"time": 1680753863440
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"categoryCode": "01",
"categoryName": "家用电器lzx",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "02",
"categoryName": "手机",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "03",
"categoryName": "电脑",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "04",
"categoryName": "家居",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "05",
"categoryName": "美妆",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "06",
"categoryName": "箱包",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "07",
"categoryName": "运动户外",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "08",
"categoryName": "汽车用品",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "09",
"categoryName": "食品",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "10",
"categoryName": "母婴",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "11",
"categoryName": "数码dcg ",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1637565445977lqoUWsxRhF.png",
"categoryLevel": 1
},
{
"categoryCode": "12",
"categoryName": "特产",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "13",
"categoryName": "玩具",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "14",
"categoryName": "个人清洁",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "15",
"categoryName": "户外",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "16",
"categoryName": "生鲜",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "17",
"categoryName": "办公",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "18",
"categoryName": "家装",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "19",
"categoryName": "厨具",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "20",
"categoryName": "家具",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "21",
"categoryName": "钟表",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "22",
"categoryName": "酒类",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "23",
"categoryName": "保健",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "24",
"categoryName": "lzx",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "28",
"categoryName": "办公家具",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "29",
"categoryName": "办公设备",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "30",
"categoryName": "办公纸品",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "31",
"categoryName": "办公耗材",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "32",
"categoryName": "办公文具用品",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "36",
"categoryName": "赠品",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "25",
"categoryName": "生活服务",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "26",
"categoryName": "视频影音",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "33",
"categoryName": "生活服务 ",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "34",
"categoryName": "美食饮品",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "35",
"categoryName": "出行权益",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "37",
"categoryName": "商超便利",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "38",
"categoryName": "测试分类信息",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1632360658394lbTeubpsKT.png",
"categoryLevel": 1
},
{
"categoryCode": "40",
"categoryName": "商户服务",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "41",
"categoryName": "生活服务/旅游",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "42",
"categoryName": "新增基础分类1022",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "43",
"categoryName": "新增2",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "44",
"categoryName": "测试分类",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "39",
"categoryName": "xd-测试一级分类",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "45",
"categoryName": "2022春晖01",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "46",
"categoryName": "2022春晖02",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "47",
"categoryName": "2022春晖03",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "48",
"categoryName": "测试虚拟分类",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "49",
"categoryName": "厨房电器",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1648438465376izYVzWhWTy.png",
"categoryLevel": 1
},
{
"categoryCode": "50",
"categoryName": "lzx一级分类",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "52",
"categoryName": "产品测试0511",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "53",
"categoryName": "1111",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1666922873744LqDZhxUeMY.png",
"categoryLevel": 1
},
{
"categoryCode": "54",
"categoryName": "3435",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "55",
"categoryName": "一级分类",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1667271393653qSKajjeaeN.png",
"categoryLevel": 1
},
{
"categoryCode": "56",
"categoryName": "一级分类1",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "57",
"categoryName": "测试一级",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1668479965351tegYHGXPMp.png",
"categoryLevel": 1
},
{
"categoryCode": "58",
"categoryName": "文件1",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1668521192309ygDFyexlRD.png",
"categoryLevel": 1
},
{
"categoryCode": "59",
"categoryName": "分类一",
"parentCategoryCode": "",
"categoryImgUrl": "",
"categoryLevel": 1
},
{
"categoryCode": "60",
"categoryName": "商品一",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1670581119197gyZdgeJRih.png",
"categoryLevel": 1
},
{
"categoryCode": "61",
"categoryName": "1",
"parentCategoryCode": "",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1670581148761USlJeFPRXe.png",
"categoryLevel": 1
}
],
"time": 1680751048243
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"tparOrderCode": "629811121721286656",
"parentOrderCode": "PO287826036798955546",
"parentOrderAmount": "320.30",
"orderFreightAmount": "0.00",
"buyerMsg": null,
"createTime": "2023-04-06 15:33:55",
"updateAddress": 0,
"orderReceiveAddress": {
"receiveName": "刘宇峰",
"receiveMobile": "18682185876",
"receivePhone": null,
"provinceId": 19,
"provinceName": "广东",
"cityId": 1607,
"cityName": "深圳市",
"countyId": 4773,
"countyName": "宝安区",
"townId": 62125,
"townName": "松岗街道",
"address": "联投东方"
},
"childOrderList": [
{
"orderCode": "287826036798955616",
"orderAmount": "320.30",
"orderStatus": 1007,
"logisticsStatus": null,
"deliverWay": 1001,
"createTime": "2023-04-06 15:34:05",
"deliverTime": null,
"confirmTime": null,
"signTime": null,
"cancelTime": null,
"orderGoodsList": [
{
"goodsSkuCode": "281474976710659",
"goodsSkuName": "HUAWEI P30 屏内指纹 双景录像 全网通手机 6+128G 极光色 ",
"goodsImageUrl": "https://img.yunzhonghe.com/image/1571480605913iYFGyDGVfN.jpg",
"brandCode": "751",
"brandName": "华为",
"firstCategoryCode": "02",
"firstCategoryName": "手机",
"secondCategoryCode": "0201",
"secondCategoryName": "手机通讯",
"lastCategoryCode": "020102",
"lastCategoryName": "手机",
"sellPrice": "320.30",
"marketPrice": "3688.00",
"sellQty": 1
}
]
}
]
}
],
"time": 1680767522098
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": {
"tparOrderCode": "629811121721286656",
"parentOrderCode": "PO287826036798955546",
"invoiceList": []
},
"time": 1680767522322
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": {
"pageNum": 1,
"pageSize": 100,
"totalCount": 2,
"totalPage": 1,
"orderList": [
{
"tparOrderCode": "629811121721286656",
"parentOrderCode": "PO287826036798955546",
"parentOrderAmount": "320.30",
"orderFreightAmount": "0.00",
"buyerMsg": null,
"childOrderList": [
{
"orderCode": "287826036798955616",
"orderAmount": "320.30",
"createTime": "2023-04-06 15:34:05"
}
]
},
{
"tparOrderCode": "629808362271907840",
"parentOrderCode": "PO287823278662393883",
"parentOrderAmount": "320.30",
"orderFreightAmount": "0.00",
"buyerMsg": null,
"childOrderList": [
{
"orderCode": "287823278662393910",
"orderAmount": "320.30",
"createTime": "2023-04-06 15:23:08"
}
]
}
]
},
"time": 1680767267803
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": {
"tparOrderCode": "629811121721286656",
"parentOrderCode": "PO287826036798955546",
"shipmentList": []
},
"time": 1680767522187
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"addressCode": "1",
"addressName": "北京",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "2",
"addressName": "上海",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "3",
"addressName": "天津",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "4",
"addressName": "重庆",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "5",
"addressName": "河北",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "6",
"addressName": "山西",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "7",
"addressName": "河南",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "8",
"addressName": "辽宁",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "9",
"addressName": "吉林",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "10",
"addressName": "黑龙江",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "11",
"addressName": "内蒙古",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "12",
"addressName": "江苏",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "13",
"addressName": "山东",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "14",
"addressName": "安徽",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "15",
"addressName": "浙江",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "16",
"addressName": "福建",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "17",
"addressName": "湖北",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "18",
"addressName": "湖南",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "19",
"addressName": "广东",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "20",
"addressName": "广西",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "21",
"addressName": "江西",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "22",
"addressName": "四川",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "23",
"addressName": "海南",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "24",
"addressName": "贵州",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "25",
"addressName": "云南",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "26",
"addressName": "西藏",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "27",
"addressName": "陕西",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "28",
"addressName": "甘肃",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "29",
"addressName": "青海",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "30",
"addressName": "宁夏",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "31",
"addressName": "新疆",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "32",
"addressName": "台湾",
"parentAddressCode": "0",
"addressLevel": 1001
},
{
"addressCode": "52993",
"addressName": "港澳",
"parentAddressCode": "0",
"addressLevel": 1001
}
],
"time": 1680750465528
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"addressCode": "62121",
"addressName": "新安街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62122",
"addressName": "西乡街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62123",
"addressName": "福永街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62124",
"addressName": "沙井街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62125",
"addressName": "松岗街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62126",
"addressName": "石岩街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62127",
"addressName": "新桥街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62128",
"addressName": "燕罗街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62129",
"addressName": "福海街道",
"parentAddressCode": "4773",
"addressLevel": 1004
},
{
"addressCode": "62130",
"addressName": "航城街道",
"parentAddressCode": "4773",
"addressLevel": 1004
}
],
"time": 1680752099380
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"categoryCode": "020101",
"categoryName": "对讲机",
"parentCategoryCode": "0201",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1565161264224RzvWlfsRwN.png",
"categoryLevel": 3
},
{
"categoryCode": "020102",
"categoryName": "手机",
"parentCategoryCode": "0201",
"categoryImgUrl": "https://img.yunzhonghe.com/image/1565161279937rUudWfFhGY.png",
"categoryLevel": 3
}
],
"time": 1680752099470
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ3VDVoNW5YV2phUHlnVEZoSEpIMHRnPT0iLCImJDE5Ml9jdXN0b21lcl9pZF8kIyEiOiJpZ3ZmQWt2L2RySjlSQ01taVlFbGdIYjRaeW5xVk5rUnRlb0x0WnJKSHBnPSIsIlF3OH5fd2Vic2l0ZV9pZF8hQCUkXiQiOiJYUVVDd0laSTA5SUdKQU5OdDZkMTdIYjRaeW5xVk5rUnRlb0x0WnJKSHBnPSIsImV4cCI6MTY4MDgzNDEzNSwiaWF0IjoxNjgwNzQ3NzM1fQ.Rfsj1N_zlWWJoRRwPExHa5mwRGHn-w2wBx0btuXEacU",
"expiresAt": "2023-04-07 10:22:15"
},
"time": 1680747735816
}
\ No newline at end of file \ No newline at end of file
{
"success": true,
"code": "00000",
"desc": "成功",
"result": [
{
"categoryCode": "0201",
"categoryName": "手机通讯",
"parentCategoryCode": "02",
"categoryImgUrl": "",
"categoryLevel": 2
},
{
"categoryCode": "0202",
"categoryName": "手机配件",
"parentCategoryCode": "02",
"categoryImgUrl": "",
"categoryLevel": 2
},
{
"categoryCode": "0203",
"categoryName": "手机周边",
"parentCategoryCode": "02",
"categoryImgUrl": "",
"categoryLevel": 2
}
],
"time": 1680751786593
}
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!-- <classPathEntry location="F://jdbc//mysql-connector-java-8.0.18.jar"/>-->
<!-- 一个数据库一个context -->
<context id="DB2Tables" targetRuntime="Mybatis3">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true"/>
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 配置 tk.mybatis 插件 -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.glsx.plat.mybatis.mapper.CommonBaseMapper"/>
</plugin>
<!--配置生成注释信息,最多配置一个 -->
<commentGenerator>
<!-- 阻止生成注释包含时间戳 默认为false -->
<property name="suppressDate" value="true"/>
<!-- 注释是否添加数据库表的备注信息 默认为false -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- jdbc连接-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.3.190:3306/scrm_account_test?serverTimeZone=Shanghai&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
userId="dev_user"
password="df234fl">
<!--防止生成其他库同名表-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="cn.com.glsx.admin.modules.entity" targetProject="../platform-auth-api/src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值去掉前后空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapper.xml文件存放地址 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成接口dao type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="cn.com.glsx.admin.modules.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
<table tableName="platform_merchant" domainObjectName="PlatformMerchant" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
\ No newline at end of file \ No newline at end of file
# framework-archetype
一、项目结构说明:
└─src
├─main
├─java
├─com.glsx.plat.gateway.common 公共方法-常量等
├─com.glsx.plat.gateway.config 系统配置
├─com.glsx.plat.gateway.exception 自定义异常处理
├─com.glsx.plat.gateway.filter 网关核心过滤器
├─com.glsx.plat.gateway.model 实体类
├─com.glsx.plat.gateway.utils 工具包
└─com.glsx.plat.gateway.GatewayApplication.java 程序入口
├─resources 资源文件目录
├─bootstrap.properties 应用配置文件
└─logback.xml 日志配置文件
└─webapp web前端文件目录
└─WEB-INF
└─bin shell脚本文件(包含启动、停止、重启等)
└─test 测试目录
├─java
└─com.glsx.plat.gateway 测试代码
└─pom.xml pom文件
二、使用说明:
1、每个调用API服务的接口,都需要先配置调用方信息,包括appKey、secret等
2、每个请求的header中需包含几个关键字段:
2.1> appKey:调用方身份标识
2.2> timestamp:请求时间戳,精确到毫秒
2.3> sign:签名,规则如下:
2.3.1> 参数排序:按照字母先后顺序,将参数进行排序,例如:将foo=1,bar=2,baz=3 排序为bar=2,baz=3,foo=1
2.3.2> 参数名和参数值链接后,得到拼装字符串bar2baz3foo1
2.3.3> 拼接上header中的timestamp和调用方的secret,得到 bar2baz3foo1 {timestamp} {secret}
2.3.4> 将上个步骤得到的字符串进行MD5加密,再转成小写就得到了签名sign
3、接口调用需经过网关层面的层层认证通过后,才会路由调用到下游方,下面是几个关键的过滤器
3.1> RecordServiceFilter:根据调用方appKey识别身份信息,校验timestamp合法性
3.2> IPCheckGlobalFilter:验证调用方IP是否在白名单内
3.3> JWTAuthGlobalFilter:验证身份认证token是否合法有效
3.4> CheckSignGlobalFilter:验证调用方的参数签名是否合法
4、
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-common-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>platform-gateway</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-gateway-server</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-exception</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-redis</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-jwt</artifactId>
</dependency>
<!--内部缓存框架统一采用caffeine-->
<!--这样Spring cloud loadbalancer用的本地实例缓存也是基于Caffeine-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-auth-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>-->
<!-- </dependency>-->
<!-- &lt;!&ndash;日志需要用log4j2&ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter</artifactId>-->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-logging</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- </dependency>-->
<!-- &lt;!&ndash;log4j2异步日志需要的依赖,所有项目都必须用log4j2和异步日志配置&ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>com.lmax</groupId>-->
<!-- <artifactId>disruptor</artifactId>-->
<!-- <version>${disruptor.version}</version>-->
<!-- </dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.0</version>
<configuration>
<fork>true</fork> <!-- 如果没有该配置,devtools不会生效 -->
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.glsx.plat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"cn.com.glsx.*.api"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package com.glsx.plat.gateway.common;
import org.springframework.core.Ordered;
public interface Constants {
String SERVICE_NAME = "SERVICE-NAME";
String GATEWAY_SERVICE_NAME = "GATEWAY_SERVICE";
//操作日志过滤器执行顺序,值越小优先级越高
int LOGGING_GLOBAL_FILTER_ORDER = Ordered.HIGHEST_PRECEDENCE;
//记录服务名
int RECORD_SERVICE_NAME_GLOBAL_FILTER_ORDER = Ordered.HIGHEST_PRECEDENCE + 1;
//防xss攻击
int XSS_REQUEST_GLOBAL_FILTER_ORDER = 1;
//防xss攻击
int XSS_RESPONSE_GLOBAL_FILTER_ORDER = 2;
//IP鉴权
int IP_CHECK_GLOBAL_FILTER_ORDER = 3;
//签名鉴权
int CHECK_SIGN_GLOBAL_FILTER_ORDER = 4;
//JWT鉴权
int JWT_AUTH_GLOBAL_FILTER_ORDER = 5;
}
package com.glsx.plat.gateway.config;
import cn.com.glsx.admin.config.ApiGatewayServiceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.event.EnableBodyCachingEvent;
import org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
@EnableConfigurationProperties({ApiGatewayRetryConfig.class, ApiGatewayServiceConfig.class})
//@LoadBalancerClients(defaultConfiguration = CommonLoadBalancerConfig.class)
public class ApiGatewayConfig {
@Autowired
private AdaptCachedBodyGlobalFilter adaptCachedBodyGlobalFilter;
@Autowired
private GatewayProperties gatewayProperties;
@PostConstruct
public void init() {
//让每一个路径都做body Cache,这样重试有Body的请求的时候,重试的请求不会没有body,因为原始body是一次性的基于netty的FluxReceive
gatewayProperties.getRoutes().forEach(routeDefinition -> {
EnableBodyCachingEvent enableBodyCachingEvent = new EnableBodyCachingEvent(new Object(), routeDefinition.getId());
adaptCachedBodyGlobalFilter.onApplicationEvent(enableBodyCachingEvent);
});
}
}
package com.glsx.plat.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.codec.support.DefaultServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
/**
* 跨域配置
*/
@Configuration
public class ApiGatewayCorsConfig {
private static final String MAX_AGE = "18000L";
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (CorsUtils.isCorsRequest(request)) {
HttpHeaders requestHeaders = request.getHeaders();
ServerHttpResponse response = ctx.getResponse();
HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
HttpHeaders headers = response.getHeaders();
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
if (requestMethod != null) {
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
}
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
@Bean
public ServerCodecConfigurer serverCodecConfigurer() {
return new DefaultServerCodecConfigurer();
}
}
package com.glsx.plat.gateway.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.factory.RetryGatewayFilterFactory;
import java.util.Map;
@Data
@ConfigurationProperties(prefix = "spring.cloud.gateway")
public class ApiGatewayRetryConfig {
private Map<String, RetryGatewayFilterFactory.RetryConfig> retry;
public RetryGatewayFilterFactory.RetryConfig getDefault() {
return retry.computeIfAbsent("default", key -> new RetryGatewayFilterFactory.RetryConfig());
}
}
package com.glsx.plat.gateway.exception;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/**
* @author payu
*/
@Slf4j
@Component
public class GlobalErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
//简单返回
if (Objects.isNull(options)) return assembleError(request);
Map<String, Object> map = super.getErrorAttributes(request, options);
if (getError(request) instanceof GlobalException) {
GlobalException ex = (GlobalException) getError(request);
map.put(R.MSG_KEY, ex.getMessage());
map.put(R.CODE_KEY, ex.getStatus().value());
return map;
}
map.put(R.CODE_KEY, map.getOrDefault("status", HttpStatus.INTERNAL_SERVER_ERROR.value()));
map.put(R.MSG_KEY, "System Error , Check logs!");
return map;
}
private Map<String, Object> assembleError(ServerRequest request) {
Map<String, Object> errorAttributes = new LinkedHashMap<>();
Throwable error = getError(request);
if (error instanceof GlobalException) {
GlobalException ex = (GlobalException) getError(request);
errorAttributes.put(R.CODE_KEY, ex.getStatus().value());
errorAttributes.put(R.MSG_KEY, ex.getMessage());
} else {
errorAttributes.put(R.CODE_KEY, HttpStatus.INTERNAL_SERVER_ERROR.value());
errorAttributes.put(R.MSG_KEY, "INTERNAL SERVER ERROR");
}
return errorAttributes;
}
}
package com.glsx.plat.gateway.exception;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;
import java.util.Map;
/**
* @author payu
*/
@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
public GlobalErrorWebExceptionHandler(GlobalErrorAttributes g, ApplicationContext applicationContext,
ServerCodecConfigurer serverCodecConfigurer) {
super(g, new WebProperties.Resources(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters());
super.setMessageReaders(serverCodecConfigurer.getReaders());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(final ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) {
final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, false);
return ServerResponse.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(errorPropertiesMap));
}
}
package com.glsx.plat.gateway.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
/**
* @author payu
*/
public class GlobalException extends ResponseStatusException {
public GlobalException(HttpStatus status, String message) {
super(status, message);
}
public GlobalException(HttpStatus status, String message, Throwable e) {
super(status, message, e);
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.gateway.filter;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
public abstract class AbstractSpecificPathFilter implements GlobalFilter, Ordered {
private final AntPathMatcher MATCHER = new AntPathMatcher();
protected final LoadingCache<String, Boolean> FILTER_CACHE = Caffeine.newBuilder().build(key -> {
String[] split = key.split(",");
HttpMethod httpMethod = HttpMethod.valueOf(split[0]);
Map<String, List<HttpMethod>> paths = getPaths();
for (String path : paths.keySet()) {
if (MATCHER.match(path, split[1])) {
List<HttpMethod> httpMethods = paths.get(path);
if (CollectionUtils.isEmpty(httpMethods)) {
return true;
} else if (httpMethods.contains(httpMethod)) {
return true;
}
}
}
return false;
});
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
if (shouldBeFiltered(exchange)) {
return filter0(exchange, chain);
}
return chain.filter(exchange);
}
/**
* 是否要经过这个filter
*
* @param exchange
* @return true则经过,false则跳过
*/
protected boolean shouldBeFiltered(ServerWebExchange exchange) {
ServerHttpRequest request = exchange.getRequest();
String path = request.getPath().value();
return FILTER_CACHE.get(request.getMethod() + "," + path);
}
protected abstract Mono<Void> filter0(ServerWebExchange exchange, GatewayFilterChain chain);
protected abstract Map<String, List<HttpMethod>> getPaths();
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.gateway.filter;
import cn.com.glsx.admin.model.GatewayService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.utils.SignUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.gateway.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.Environment;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.multipart.Part;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.*;
/**
* 验签
*
* @author payu
*/
@Slf4j
@Component
public class CheckSignGlobalFilter implements GlobalFilter, Ordered {
@Autowired
private Environment env;
//保存HttpMessageReader
private static final List<HttpMessageReader<?>> MESSAGE_READERS = HandlerStrategies.withDefaults().messageReaders();
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
// 请求参数上的url地址
log.info("访问地址:{}", request.getURI());
if (!env.getProperty("gateway.sign.switch", Boolean.class, false)){
return chain.filter(exchange);
}
GatewayService gatewayService = exchange.getAttribute(Constants.GATEWAY_SERVICE_NAME);
//调用方是否开启鉴权
if(!gatewayService.getCheckSign()){
return chain.filter(exchange);
}
Map<String, String> params = new HashMap<>();
request.getQueryParams().forEach((key, items) -> {
params.put(key, items.get(0));
});
String sign = request.getHeaders().getFirst("sign");
params.put("sign", sign);
if (HttpMethod.GET.name().equals(request.getMethodValue())) {
return this.checkSign(params, gatewayService.getSecret(), chain, exchange);
} else if (HttpMethod.POST.name().equals(request.getMethodValue())) {
return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
DataBufferUtils.retain(dataBuffer);
final Flux<DataBuffer> cachedFlux = Flux.defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
final ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public Flux<DataBuffer> getBody() {
return cachedFlux;
}
};
final ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
return cacheBody(params, gatewayService.getSecret(), chain, mutatedExchange);
});
}
return chain.filter(exchange);
}
/**
* 验证签名
* @param params:
* @param secret:
* @param chain:
* @param exchange:
* @return reactor.core.publisher.Mono<java.lang.Void>
* @author huangch
* @date 2023/4/6 15:36
*/
private Mono<Void> checkSign(Map<String, String> params, String secret, GatewayFilterChain chain, ServerWebExchange exchange) {
log.info("校验参数集合:" + params);
if (!SignUtils.checkSign(params, secret)) {
// 返回json格式
exchange.getResponse().setStatusCode(HttpStatus.OK);
exchange.getResponse().getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(R.error(HttpStatus.FORBIDDEN.value(), "签名验证失败")).getBytes())));
}
return chain.filter(exchange);
}
@SuppressWarnings("unchecked")
private Mono<Void> cacheBody(Map<String, String> params, String secret, GatewayFilterChain chain, ServerWebExchange exchange) {
final HttpHeaders headers = exchange.getRequest().getHeaders();
if (headers.getContentLength() == 0) {
return chain.filter(exchange);
}
final ResolvableType resolvableType;
if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(headers.getContentType())) {
resolvableType = ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Part.class);
} else if (MediaType.APPLICATION_JSON.isCompatibleWith(headers.getContentType()) || MediaType.APPLICATION_JSON_UTF8.isCompatibleWith(headers.getContentType())) {
resolvableType = ResolvableType.forClass(JSONObject.class);//必须是Object不能是Array,带sign字段
} else {
resolvableType = ResolvableType.forClass(String.class);
}
return MESSAGE_READERS.stream().filter(reader -> reader.canRead(resolvableType,
exchange.getRequest().getHeaders().getContentType())).findFirst()
.orElseThrow(() -> new IllegalStateException("no suitable HttpMessageReader.")).readMono(resolvableType,
exchange.getRequest(), Collections.emptyMap()).flatMap(resolvedBody -> {
if (resolvedBody instanceof MultiValueMap) {
@SuppressWarnings("rawtypes")
MultiValueMap<String, Object> map = (MultiValueMap) resolvedBody;
map.keySet().forEach(key -> {
// SynchronossPartHttpMessageReader
Object obj = map.get(key);
List<Object> list = (List<Object>) obj;
for (Object object : list) {
if (object.getClass().toString().equals("class org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader$SynchronossFilePart")) {
continue;
}
Field[] fields = object.getClass().getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
params.put(key, field.get(object) + "");
}
} catch (IllegalAccessException e) {
e.printStackTrace();
log.info(e.getLocalizedMessage());
}
}
});
} else if (resolvedBody instanceof JSONObject) {
@SuppressWarnings("rawtypes")
JSONObject bodyObj = (JSONObject) resolvedBody;
Iterator iter = bodyObj.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
params.put(entry.getKey().toString(), String.valueOf(entry.getValue()));
}
} else {
if (null != resolvedBody) {
String path = null;
try {
path = URLDecoder.decode(resolvedBody.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
log.error(e.getLocalizedMessage());
}
if (null != path) {
String items[] = path.split("&");
for (String item : items) {
String subItems[] = item.split("=");
if (subItems.length == 2) {
params.put(subItems[0], subItems[1]);
}
}
}
}
}
return this.checkSign(params, secret, chain, exchange);
});
}
@Override
public int getOrder() {
return Constants.CHECK_SIGN_GLOBAL_FILTER_ORDER;
}
}
//package com.glsx.plat.gateway.filter;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.glsx.plat.common.utils.SignUtils;
//import com.glsx.plat.core.web.R;
//import com.glsx.plat.gateway.common.Constants;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.core.ResolvableType;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.core.io.buffer.DataBufferUtils;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpMethod;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.http.codec.HttpMessageReader;
//import org.springframework.http.codec.multipart.Part;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
//import org.springframework.util.MultiValueMap;
//import org.springframework.web.reactive.function.server.HandlerStrategies;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//import java.io.UnsupportedEncodingException;
//import java.lang.reflect.Field;
//import java.net.URLDecoder;
//import java.util.*;
//
///**
// * 验签
// *
// * @author payu
// */
//@Slf4j
////@Component
//public class CheckSignGlobalFilterBak implements GlobalFilter, Ordered {
//
// @Value("${gateway.sign.switch:off}")
// private String signSwitch;
//
// @Value("${gateway.sign.secret}")
// private String signSecret;
//
// //保存HttpMessageReader
// private static final List<HttpMessageReader<?>> MESSAGE_READERS = HandlerStrategies.withDefaults().messageReaders();
//
// @Override
// public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// ServerHttpRequest request = exchange.getRequest();
// log.info("访问地址:{}", request.getURI().toString());
//
// // 请求参数上的url地址
// Map<String, String> params = new HashMap<>();
// request.getQueryParams().forEach((key, items) -> {
// params.put(key, items.get(0));
// });
// if (HttpMethod.GET.name().equals(request.getMethodValue())) {
// return this.checkSign(params, chain, exchange);
// } else if (HttpMethod.POST.name().equals(request.getMethodValue())) {
// return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
// DataBufferUtils.retain(dataBuffer);
// final Flux<DataBuffer> cachedFlux = Flux.defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
// final ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
// @Override
// public Flux<DataBuffer> getBody() {
// return cachedFlux;
// }
// };
// final ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
//
// return cacheBody(mutatedExchange, chain, params);
// });
//
// }
// return chain.filter(exchange);
// }
//
// /***
//  * 验证签名
//  * @author Lance lance_lan_2016@163.com
//  * @date 2020-01-07 09:57
//  * @param params
//  * @param chain
//  * @param exchange
//  * @return reactor.core.publisher.Mono<java.lang.Void>
//  *
//  * */
// private Mono<Void> checkSign(Map<String, String> params, GatewayFilterChain chain, ServerWebExchange exchange) {
// if (!"on".equalsIgnoreCase(signSwitch)) return chain.filter(exchange);
//
// log.info("校验参数集合:" + params);
// if (!SignUtils.checkSign(params, signSecret)) {
// // 返回json格式
// exchange.getResponse().setStatusCode(HttpStatus.OK);
// exchange.getResponse().getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
// return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(R.error(HttpStatus.FORBIDDEN.value(), "签名验证失败")).getBytes())));
// }
// return chain.filter(exchange);
// }
//
// @SuppressWarnings("unchecked")
// private Mono<Void> cacheBody(ServerWebExchange exchange, GatewayFilterChain chain, Map<String, String> params) {
// final HttpHeaders headers = exchange.getRequest().getHeaders();
// if (headers.getContentLength() == 0) {
// return chain.filter(exchange);
// }
// final ResolvableType resolvableType;
// if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(headers.getContentType())) {
// resolvableType = ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Part.class);
// } else if (MediaType.APPLICATION_JSON.isCompatibleWith(headers.getContentType()) || MediaType.APPLICATION_JSON_UTF8.isCompatibleWith(headers.getContentType())) {
// resolvableType = ResolvableType.forClass(JSONObject.class);//必须是Object不能是Array,带sign字段
// } else {
// resolvableType = ResolvableType.forClass(String.class);
// }
//
// return MESSAGE_READERS.stream().filter(reader -> reader.canRead(resolvableType,
// exchange.getRequest().getHeaders().getContentType())).findFirst()
// .orElseThrow(() -> new IllegalStateException("no suitable HttpMessageReader.")).readMono(resolvableType,
// exchange.getRequest(), Collections.emptyMap()).flatMap(resolvedBody -> {
// if (resolvedBody instanceof MultiValueMap) {
// @SuppressWarnings("rawtypes")
// MultiValueMap<String, Object> map = (MultiValueMap) resolvedBody;
// map.keySet().forEach(key -> {
// // SynchronossPartHttpMessageReader
// Object obj = map.get(key);
// List<Object> list = (List<Object>) obj;
// for (Object object : list) {
// if (object.getClass().toString().equals("class org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader$SynchronossFilePart")) {
// continue;
// }
// Field[] fields = object.getClass().getDeclaredFields();
// try {
// for (Field field : fields) {
// field.setAccessible(true);
// params.put(key, field.get(object) + "");
// }
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// log.info(e.getLocalizedMessage());
// }
// }
// });
// } else if (resolvedBody instanceof JSONObject) {
// @SuppressWarnings("rawtypes")
// JSONObject bodyObj = (JSONObject) resolvedBody;
//
// Iterator iter = bodyObj.entrySet().iterator();
// while (iter.hasNext()) {
// Map.Entry entry = (Map.Entry) iter.next();
// params.put(entry.getKey().toString(), String.valueOf(entry.getValue()));
// }
// } else {
// if (null != resolvedBody) {
// String path = null;
// try {
// path = URLDecoder.decode(resolvedBody.toString(), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// log.error(e.getLocalizedMessage());
// }
// if (null != path) {
// String items[] = path.split("&");
// for (String item : items) {
// String subItems[] = item.split("=");
// if (subItems.length == 2) {
// params.put(subItems[0], subItems[1]);
// }
// }
// }
// }
// }
// return this.checkSign(params, chain, exchange);
// });
// }
//
// @Override
// public int getOrder() {
// return Constants.CHECK_SIGN_GLOBAL_FILTER_ORDER;
// }
//
//}
package com.glsx.plat.gateway.filter;
import cn.com.glsx.admin.config.ApiGatewayServiceConfig;
import cn.com.glsx.admin.model.GatewayService;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.core.web.R;
import com.glsx.plat.gateway.common.Constants;
import com.glsx.plat.gateway.utils.GatewayIpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;
/**
* @author huangch
* @version V1.0
* @Title: IpCheckGlobalFilter
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/4 10:59
*/
@Slf4j
@Component
@RefreshScope
public class IPCheckGlobalFilter implements GlobalFilter, Ordered {
@Autowired
private ApiGatewayServiceConfig consumerConfig;
private static final String APP_KEY = "appKey";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
GatewayService gatewayService = exchange.getAttribute(Constants.GATEWAY_SERVICE_NAME);
//判断鉴权开关是否打开
if(!gatewayService.getIpAuth()){
return chain.filter(exchange);
}
//获取请求方真实IP
String requestIp = GatewayIpUtils.getIpAddr(request);
//判断请求方IP是否在白名单内
List<String> whiteIps = Arrays.asList(gatewayService.getWhiteIps().split(","));
if(whiteIps.contains(requestIp)){
return chain.filter(exchange);
}
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.FORBIDDEN);
return response.writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(R.error(HttpStatus.FORBIDDEN.value(), "IP NO IN WHITE LIST")).getBytes())));
}
@Override
public int getOrder() {
return Constants.IP_CHECK_GLOBAL_FILTER_ORDER;
}
}
package com.glsx.plat.gateway.filter;
import cn.com.glsx.admin.model.GatewayService;
import cn.com.glsx.admin.utils.GatewayJwtUtils;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.gateway.common.Constants;
import com.glsx.plat.jwt.base.ComJwtUser;
import com.glsx.plat.jwt.config.JwtConfigProperties;
import com.glsx.plat.jwt.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* @author payu
*/
@Slf4j
@Component
@RefreshScope
public class JWTAuthGlobalFilter implements GlobalFilter, Ordered {
@Value("${auth.skip.urls:#{null}}")
private String[] skipAuthUrls;
@Autowired
private JwtConfigProperties properties;
@Autowired
private GatewayJwtUtils gatewayJwtUtils;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public int getOrder() {
return Constants.JWT_AUTH_GLOBAL_FILTER_ORDER;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
GatewayService gatewayService = exchange.getAttribute(Constants.GATEWAY_SERVICE_NAME);
if(!gatewayService.getJwtAuth()){
return chain.filter(exchange);
}
String url = exchange.getRequest().getURI().getPath();
//跳过不需要验证的路径
if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
return chain.filter(exchange);
}
//api接口不需要验证
String[] urlPaths = url.split("/");
if (!CollectionUtils.sizeIsEmpty(urlPaths)) {
List<String> list = new ArrayList<>(Arrays.asList(urlPaths));
if (list.contains("api") || list.contains("API")) {
return chain.filter(exchange);
}
}
//从请求头中取出token
String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
//未携带token或token在黑名单内
if (token == null || token.isEmpty() || isBlackToken(token)) {
log.info("url {} token is empty", url);
return loginResponse(exchange, token);
}
//验证token
// TODO: 2020/11/5 如果失效会报错,在失效情况下,失效刷新时间范围内,允许刷新
DecodedJWT decodedJWT = gatewayJwtUtils.verify(token, gatewayService);
if (decodedJWT == null) {
log.info("url {} token decoded fail", url);
return loginResponse(exchange, token);
}
ServerHttpRequest mutableReq = appendRequestHeaders(exchange, decodedJWT.getId());
ServerHttpResponse mutableResp = appendResponseHeaders(exchange, token);
ServerWebExchange mutableExchange = exchange.mutate()
.request(mutableReq)
.response(mutableResp)
.build();
return chain.filter(mutableExchange);
}
public Mono<Void> loginResponse(ServerWebExchange exchange, String token) {
ServerHttpResponse originalResponse = exchange.getResponse();
originalResponse.setStatusCode(HttpStatus.OK);
originalResponse.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
originalResponse.getHeaders().add(HttpHeaders.FROM, "Gateway");
log.info("invalid token [{}]", token);
String notLoginJson = JSON.toJSONString(R.error(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg()));
byte[] response = notLoginJson.getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
return originalResponse.writeWith(Flux.just(buffer));
}
public ServerHttpRequest appendRequestHeaders(ServerWebExchange exchange, String jwtId) {
// //将现在的request,添加当前身份
return exchange.getRequest().mutate()
.header("Authorization-UserId", jwtId)
.build();
}
public ServerHttpResponse appendResponseHeaders(ServerWebExchange exchange, String token) {
ServerHttpResponse mutableResp = exchange.getResponse();
mutableResp.getHeaders().add(HttpHeaders.AUTHORIZATION, token);
return mutableResp;
}
/**
* 判断token是否在黑名单内
*
* @param token
* @return
*/
private boolean isBlackToken(String token) {
assert token != null;
if (StringUtils.isEmpty(properties.getBlacklistKey())) {
return false;
}
return false;
//return stringRedisTemplate.hasKey(String.format(properties.getBlacklistKey(), token));
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.gateway.filter;
import com.glsx.plat.gateway.common.Constants;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class LoggingGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange.mutate().request(new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public Flux<DataBuffer> getBody() {
//body开启日志,记录操作body的filter
return exchange.getRequest().getBody().log();
}
}).build());
}
@Override
public int getOrder() {
return Constants.LOGGING_GLOBAL_FILTER_ORDER;
}
}
package com.glsx.plat.gateway.filter;
import cn.com.glsx.admin.config.ApiGatewayServiceConfig;
import cn.com.glsx.admin.model.GatewayService;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.gateway.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Slf4j
@Component
public class RecordServiceFilter implements GlobalFilter, Ordered {
@Autowired
private ApiGatewayServiceConfig apiGatewayServiceConfig;
@Autowired
private Environment env;
private static final String APP_KEY = "appKey";
private static final String TIMESTAMP = "timestamp";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
//校验请求的时间戳
String timestamp = request.getHeaders().getFirst(TIMESTAMP);
if(StringUtils.isEmpty(timestamp)){
log.warn("缺少请求参数timestamp");
return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(R.error(HttpStatus.FORBIDDEN.value(), "Time Error.")).getBytes())));
}
long timeout = env.getProperty("gateway.sign.timeout", Long.class, 5 * 60 * 1000L);
long diff = System.currentTimeMillis() - Long.parseLong(timestamp);
if(diff < 0 || diff > timeout){
log.warn("请求参数timestamp不在系统允许的范围内");
return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(R.error(HttpStatus.FORBIDDEN.value(), "Time Error.")).getBytes())));
}
//校验请求头是否携带appKey参数
String appKey = request.getHeaders().getFirst(APP_KEY);
if(StringUtils.isEmpty(appKey)){
log.warn("缺少请求参数appKey");
return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(R.error(HttpStatus.FORBIDDEN.value(), "Sign Error.")).getBytes())));
}
//appKey是否正确
GatewayService gatewayService = apiGatewayServiceConfig.getServiceByAppKey(appKey);
if(gatewayService == null){
log.warn("appKey对应的调用方不存在");
return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(R.error(HttpStatus.FORBIDDEN.value(), "Sign Error.")).getBytes())));
}
exchange.getAttributes().put(Constants.GATEWAY_SERVICE_NAME, gatewayService);
Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
String host = route.getUri().getHost();
return chain.filter(exchange.mutate().request(new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public HttpHeaders getHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(exchange.getRequest().getHeaders());
httpHeaders.set(Constants.SERVICE_NAME, host);
return httpHeaders;
}
}).build());
}
@Override
public int getOrder() {
return Constants.RECORD_SERVICE_NAME_GLOBAL_FILTER_ORDER;
}
}
package com.glsx.plat.gateway.filter;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.gateway.common.Constants;
import com.glsx.plat.gateway.utils.XssCleanRuleUtils;
import io.netty.buffer.ByteBufAllocator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自定义防XSS攻击网关全局过滤器
*/
@Slf4j
@Component
public class XssRequestGlobalFilter implements GlobalFilter, Ordered {
/**
* @param exchange
* @param chain
* @return get请求参考spring cloud gateway自带过滤器:
* @see org.springframework.cloud.gateway.filter.factory.AddRequestParameterGatewayFilterFactory
* <p>
* post请求参考spring cloud gateway自带过滤器:
* @see org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// grab configuration from Config object
log.debug("----自定义防XSS攻击网关全局过滤器生效----");
ServerHttpRequest serverHttpRequest = exchange.getRequest();
HttpMethod method = serverHttpRequest.getMethod();
String contentType = serverHttpRequest.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
Boolean postFlag = (method == HttpMethod.POST || method == HttpMethod.PUT) &&
(MediaType.APPLICATION_FORM_URLENCODED_VALUE.equalsIgnoreCase(contentType) || MediaType.APPLICATION_JSON_VALUE.equals(contentType) || MediaType.APPLICATION_JSON_UTF8_VALUE.equals(contentType));
// get 请求, 参考的是 org.springframework.cloud.gateway.filter.factory.AddRequestParameterGatewayFilterFactory
if (method == HttpMethod.GET) {
URI uri = exchange.getRequest().getURI();
String rawQuery = uri.getRawQuery();
if (StringUtils.isBlank(rawQuery)) {
return chain.filter(exchange);
}
rawQuery = XssCleanRuleUtils.xssClean(rawQuery);
try {
URI newUri = UriComponentsBuilder.fromUri(uri)
.replaceQuery(rawQuery)
.build(true)
.toUri();
ServerHttpRequest request = exchange.getRequest().mutate()
.uri(newUri).build();
return chain.filter(exchange.mutate().request(request).build());
} catch (Exception e) {
log.error("get请求清理xss攻击异常", e);
throw new IllegalStateException("Invalid URI query: \"" + rawQuery + "\"");
}
}
//post请求时,如果是文件上传之类的请求,不修改请求消息体
else if (postFlag) {
// 参考的是 org.springframework.cloud.gateway.filter.factory.AddRequestParameterGatewayFilterFactory
//从请求里获取Post请求体
String bodyStr = resolveBodyFromRequest(serverHttpRequest);
// 这种处理方式,必须保证post请求时,原始post表单必须有数据过来,不然会报错
if (StringUtils.isBlank(bodyStr)) {
log.error("请求异常:{} POST请求必须传递参数", serverHttpRequest.getURI().getRawPath());
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.BAD_REQUEST);
String notLoginJson = JSON.toJSONString(R.error(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg()));
byte[] bytes = notLoginJson.getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bytes);
return response.writeWith(Mono.just(buffer));
}
bodyStr = XssCleanRuleUtils.xssClean(bodyStr);
URI uri = serverHttpRequest.getURI();
URI newUri = UriComponentsBuilder.fromUri(uri).build(true).toUri();
ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri).build();
DataBuffer bodyDataBuffer = stringBuffer(bodyStr);
Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);
// 定义新的消息头
HttpHeaders headers = new HttpHeaders();
headers.putAll(exchange.getRequest().getHeaders());
// 由于修改了传递参数,需要重新设置CONTENT_LENGTH,长度是字节长度,不是字符串长度
int length = bodyStr.getBytes().length;
headers.remove(HttpHeaders.CONTENT_LENGTH);
headers.setContentLength(length);
// 设置CONTENT_TYPE
if (StringUtils.isNotBlank(contentType)) {
headers.set(HttpHeaders.CONTENT_TYPE, contentType);
}
// 由于post的body只能订阅一次,由于上面代码中已经订阅过一次body。所以要再次封装请求到request才行,不然会报错请求已经订阅过
request = new ServerHttpRequestDecorator(request) {
@Override
public HttpHeaders getHeaders() {
long contentLength = headers.getContentLength();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(super.getHeaders());
if (contentLength > 0) {
httpHeaders.setContentLength(contentLength);
} else {
// this causes a 'HTTP/1.1 411 Length Required' on httpbin.org
httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
}
return httpHeaders;
}
@Override
public Flux<DataBuffer> getBody() {
return bodyFlux;
}
};
//封装request,传给下一级
request.mutate().header(HttpHeaders.CONTENT_LENGTH, Integer.toString(bodyStr.length()));
return chain.filter(exchange.mutate().request(request).build());
} else {
return chain.filter(exchange);
}
}
@Override
public int getOrder() {
return Constants.XSS_REQUEST_GLOBAL_FILTER_ORDER;
}
/**
* 从Flux<DataBuffer>中获取字符串的方法
*
* @return 请求体
*/
private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
//获取请求体
Flux<DataBuffer> body = serverHttpRequest.getBody();
AtomicReference<String> bodyRef = new AtomicReference<>();
body.subscribe(buffer -> {
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
DataBufferUtils.release(buffer);
bodyRef.set(charBuffer.toString());
});
//获取request body
return bodyRef.get();
}
/**
* 字符串转DataBuffer
*
* @param value
* @return
*/
private DataBuffer stringBuffer(String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length);
buffer.write(bytes);
return buffer;
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.gateway.filter;
import com.glsx.plat.gateway.common.Constants;
import com.glsx.plat.gateway.utils.XssCleanRuleUtils;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
/**
* 重写Response,防止xss攻击
*/
@Slf4j
@Component
public class XssResponseGlobalFilter implements Ordered, GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse originalResponse = exchange.getResponse();
DataBufferFactory bufferFactory = originalResponse.bufferFactory();
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
String contentType = getDelegate().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
boolean flag = MediaType.APPLICATION_JSON_VALUE.equals(contentType) || MediaType.APPLICATION_JSON_UTF8_VALUE.equals(contentType);
if (body instanceof Flux && flag) {
Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
return super.writeWith(fluxBody.map(dataBuffer -> {
// probably should reuse buffers
byte[] content = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(content);
//释放掉内存
DataBufferUtils.release(dataBuffer);
String result = new String(content, StandardCharsets.UTF_8);
//result就是response的值,对result进行去XSS
result = XssCleanRuleUtils.xssClean(result);
byte[] uppedContent = new String(result.getBytes(), StandardCharsets.UTF_8).getBytes();
return bufferFactory.wrap(uppedContent);
}));
}
// if body is not a flux. never got there.
return super.writeWith(body);
}
};
// replace response with decorator
return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
@Override
public int getOrder() {
return Constants.XSS_RESPONSE_GLOBAL_FILTER_ORDER;
}
}
package com.glsx.plat.gateway.utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author huangch
* @version V1.0
* @Title: GatewayIpUtils
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/4 11:28
*/
public class GatewayIpUtils {
private static final Logger log = LoggerFactory.getLogger(GatewayIpUtils.class);
// 多次反向代理后会有多个ip值 的分割符
private final static String IP_UTILS_FLAG = ",";
// 未知IP
private final static String UNKNOWN = "unknown";
// 本地 IP
private final static String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
private final static String LOCALHOST_IP1 = "127.0.0.1";
public static String getIpAddr(ServerHttpRequest request) {
// 根据 HttpHeaders 获取 请求 IP地址
String ip = request.getHeaders().getFirst("X-Forwarded-For");
if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("x-forwarded-for");
if (ip != null && ip.length() != 0 && !UNKNOWN.equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if (ip.contains(IP_UTILS_FLAG)) {
ip = ip.split(IP_UTILS_FLAG)[0];
}
}
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("X-Real-IP");
}
//兼容k8s集群获取ip
if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddress().getAddress().getHostAddress();
if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
//根据网卡取本机配置的IP
InetAddress iNet = null;
try {
iNet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
log.error("getClientIp error: ", e);
}
ip = iNet.getHostAddress();
}
}
return ip;
}
}
package com.glsx.plat.gateway.utils;
import java.util.regex.Pattern;
/**
* xss过滤工具
*/
public class XssCleanRuleUtils {
private final static Pattern[] scriptPatterns = {
Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),
Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),
Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)
};
public static String xssClean(String value) {
if (value != null) {
value = value.replaceAll("\0|\n|\r", "");
for (Pattern pattern : scriptPatterns) {
value = pattern.matcher(value).replaceAll("");
}
value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
}
return value;
}
}
spring.application.name=rest-admin-gateway
server.port=8080
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
spring.main.allow-bean-definition-overriding=true
#nacos config center
spring.cloud.nacos.config.server-addr=192.168.0.63:8868
spring.cloud.nacos.config.group=PLATFORM_GROUP
spring.cloud.nacos.config.prefix=${spring.application.name}
spring.profiles.active=dev
#spring.cloud.nacos.config.file-extension=properties
spring.cloud.nacos.config.file-extension=yaml
spring.main.allow-circular-references=true
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=platform-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].data-id=platform-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[1].refresh=true
#share config
spring.cloud.nacos.config.shared-configs[2].data-id=plateform-gateway-dev.yaml
spring.cloud.nacos.config.shared-configs[2].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[2].refresh=true
#鉴权公共配置
spring.cloud.nacos.config.shared-configs[3].data-id=plateform-auth-common-dev.yaml
spring.cloud.nacos.config.shared-configs[3].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[3].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 配置日志输出参数 -->
<property name="CONSOLE_LOG_PATTERN"
value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}.json</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<timestamp>
<timeZone>UTC</timeZone>
</timestamp>
<pattern>
<pattern>
{
"severity": "%level",
"service": "${APP_NAME:-}",
"trace": "%X{X-B3-TraceId:-}",
"span": "%X{X-B3-SpanId:-}",
"parent": "%X{X-B3-ParentSpanId:-}",
"exportable": "%X{X-Span-Export:-}",
"pid": "${PID:-}",
"thread": "%thread",
"class": "%logger{40}",
"rest": "%message"
}
</pattern>
</pattern>
</providers>
</encoder>
</appender>
​
<root level="INFO">
<appender-ref ref="console"/>
<!-- uncomment this to have also JSON logs -->
<appender-ref ref="logstash"/>
<!--<appender-ref ref="flatfile"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8768"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="com.glsx.plat.GatewayApplication"
SERVER_NAME="glsx-rest-admin-gateway-server"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file \ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="glsx-rest-admin-gateway-server"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file \ No newline at end of file
package com.glsx.gateway;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
}
package com.glsx.gateway;
/**
* @author huangch
* @version V1.0
* @Title: Test
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/6 16:27
*/
public class Test {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-archetype-parent</artifactId>
<groupId>com.glsx</groupId>
<version>2.0.0-SNAPSHOT</version>
<relativePath/>
</parent>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-common-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<description>Microservice Scaffolding project for Spring Boot</description>
<modules>
<module>platform-auth</module>
<module>platform-auth-api</module>
<module>platform-gateway</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!