Commit 84bd11be by 刘宇峰

平台网关

0 parents
Showing 30 changed files with 1996 additions and 0 deletions
# 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>com.glsx</groupId>
<artifactId>rest-admin-framework</artifactId>
<version>2.0.0-SNAPSHOT</version>
<relativePath/>
</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>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<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 cn.com.glsx;
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(scanBasePackages = {"cn.com.glsx.*"}, 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 cn.com.glsx.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 cn.com.glsx.gateway.config;
import cn.com.glsx.auth.config.ApiGatewayServiceConfig;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
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.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import javax.annotation.PostConstruct;
import java.util.stream.Collectors;
@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);
});
}
@Bean
@ConditionalOnMissingBean
public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
}
}
package cn.com.glsx.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 cn.com.glsx.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 cn.com.glsx.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);
Throwable throwable = getError(request);
map.put(R.MSG_KEY, throwable.getMessage());
map.put(R.CODE_KEY, HttpStatus.INTERNAL_SERVER_ERROR.value());
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 cn.com.glsx.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 cn.com.glsx.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 cn.com.glsx.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 cn.com.glsx.gateway.filter;
//
//import cn.com.glsx.auth.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 cn.com.glsx.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 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 cn.com.glsx.gateway.filter;
import cn.com.glsx.auth.model.GatewayService;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.core.web.R;
import cn.com.glsx.gateway.common.Constants;
import cn.com.glsx.gateway.utils.GatewayIpUtils;
import lombok.extern.slf4j.Slf4j;
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.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;
import java.util.Objects;
/**
* @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 {
@Value("${gateway.skip.urls:#{null}}")
private String[] skipAuthUrls;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String url = exchange.getRequest().getURI().getPath();
//跳过不需要验证的路径
if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
return chain.filter(exchange);
}
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 cn.com.glsx.gateway.filter;
import cn.com.glsx.auth.model.GatewayService;
import cn.com.glsx.auth.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 cn.com.glsx.gateway.common.Constants;
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("${gateway.skip.urls:#{null}}")
private String[] skipAuthUrls;
@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) {
String url = exchange.getRequest().getURI().getPath();
//跳过不需要验证的路径
if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
return chain.filter(exchange);
}
GatewayService gatewayService = exchange.getAttribute(Constants.GATEWAY_SERVICE_NAME);
if(!gatewayService.getJwtAuth()){
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()) {
return loginResponse(exchange, token);
}
//验证token
// TODO: 2020/11/5 如果失效会报错,在失效情况下,失效刷新时间范围内,允许刷新
DecodedJWT decodedJWT = gatewayJwtUtils.verify(token, gatewayService);
if (decodedJWT == null) {
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;
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.gateway.filter;
import cn.com.glsx.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 cn.com.glsx.gateway.filter;
import cn.com.glsx.auth.config.ApiGatewayServiceConfig;
import cn.com.glsx.auth.model.GatewayService;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import cn.com.glsx.gateway.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;
import java.util.Arrays;
import java.util.Objects;
@Slf4j
@Component
public class RecordServiceFilter implements GlobalFilter, Ordered {
@Value("${gateway.skip.urls:#{null}}")
private String[] skipAuthUrls;
@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 url = request.getURI().getPath();
//跳过不需要验证的路径
if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
return chain.filter(exchange);
}
//校验请求的时间戳
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 cn.com.glsx.gateway.filter;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import cn.com.glsx.gateway.common.Constants;
import cn.com.glsx.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 cn.com.glsx.gateway.filter;
import cn.com.glsx.gateway.common.Constants;
import cn.com.glsx.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 cn.com.glsx.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 cn.com.glsx.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=platform-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());
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!