spring-cloud-gateway引入总结(含修改响应body)
一、版本
pom.xml
<!-- 仅保留了spring系的版本 -->
<properties>
<springframework.version>5.3.22</springframework.version>
<spring-boot.version>2.3.12.RELEASE</spring-boot.version>
<spring-cloud-netflix.version>2.2.9.RELEASE</spring-cloud-netflix.version>
<spring-data.version>2.3.9.RELEASE</spring-data.version>
</properties>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.9.RELEASE</version>
</dependency>
<dependency>
<artifactId>spring-boot-starter-webflux</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.3.12.RELEASE</version>
</dependency>
二、配置文件
spring:
application:
name: gateway
cloud:
consul:
host: *.*.*.*
port: 8500
discovery:
service-name: ${spring.application.name}
prefer-ip-address: true
health-check-path: /health/check
health-check-interval: 10s
instance-id: ${spring.cloud.client.ip-address}:${server.port}
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
httpclient:
connect-timeout: 60
三、冲突问题
spring-cloud-gateway与spring-webmvc冲突,需剔除spring-webmvc,引入spring-webflux。需要替换javax.servlet.http.HttpServletRequest为org.springframework.http.server.reactive.ServerHttpRequest。获取header等的方法也要修改。
四、过滤器配置
对请求的token进行校验并对返参格式统一处理。
需注意对response的body修改,使用response.writeWith()方法即可,不必继承ServerHttpResponseDecorator等等方法。
GateWayPreFilter.java
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.io.buffer.DataBuffer;
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 *.AuthService;
import java.util.List;
@Component
@Slf4j
public class GateWayPreFilter implements GlobalFilter, Ordered {
/**
* 排除过滤的 uri 地址
*/
private static final String LOGIN_URI = "/login";
private static final String HEALTH_CHECK_URI = "/health/check";
@Autowired
private AuthService authService;
//判断是否需要过滤
public boolean notFilter(ServerHttpRequest request) {
//是否执行该过滤器
// log.info("===当前请求路径为:" + request.getURI().toString());
//注册和登录接口不拦截,其他接口都要拦截校验 token
return request.getURI().getPath().contains(LOGIN_URI) || request.getURI().getPath().contains(HEALTH_CHECK_URI);
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (notFilter(request)) {
return chain.filter(exchange);
}
ServerHttpResponse response = exchange.getResponse();
List<String> authorization = request.getHeaders().get("Authorization");
String token = null;
if (null != authorization) {
token = authorization.stream().findFirst().orElse(null);
}
HttpHeaders headers = response.getHeaders();
if (token == null || token.isEmpty()) {
response.setStatusCode(HttpStatus.OK);
//校验异常的返参格式处理,写入返参body
String body = "{\"status\":-1,\"statusText\":\"没有token\"}";
Flux<byte[]> flux = Flux.just(body.getBytes());
Flux<DataBuffer> map = flux.map(bx -> response.bufferFactory().wrap(bx));
headers.setContentType(MediaType.APPLICATION_JSON);
return response.writeWith(map);
}
//2. 进行 权限认证的 逻辑
boolean result = this.authenticate(token);
if (result) {
////通过校验
// 添加额外的请求参数为可选逻辑...
List<String> param1s = request.getHeaders().get("param1");
String param1 = null == userids ? null : param1s.stream().findFirst().orElse(null);
//把头信息转发下去,并且放行
ServerHttpRequest newRequest = request.mutate()
.header("Authorization", token)
.header("param1", param1).build();
ServerWebExchange newExchange = exchange.mutate()
.request(newRequest)
.response(response).build();
return chain.filter(newExchange);
} else {
//校验未通过
//阻止请求。
response.setStatusCode(HttpStatus.OK);
String body = "{\"status\":-1,\"statusText\":\"用户登录超时,请重新登录\"}";
Flux<byte[]> flux = Flux.just(body.getBytes());
Flux<DataBuffer> map = flux.map(bx -> response.bufferFactory().wrap(bx));
headers.setContentType(MediaType.APPLICATION_JSON);
return response.writeWith(map);
}
}
//token校验逻辑
private boolean authenticate(String token) {
return authService.authenticate(token);
}
@Override
public int getOrder() {
return -100;
}
}
五、获取IP
RequestUtils.java
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import javax.servlet.http.HttpServletRequest;
@Slf4j
public class RequestUtil {
public static String getIpAddr(HttpServletRequest request) {
if(null == request){
throw new ...;
}
String ip = null;
try {
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || "localhost".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || "localhost".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || "localhost".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || "localhost".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
log.error("RequestUtil.getIpAddr 获取请求真实ip 发生异常,异常信息为 - {} ", e);
throw new ...;
}
return ip;
}
public static String getIpAddr(ServerHttpRequest request) {
if(null == request){
throw new ...;
}
String ip = null;
try {
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || "localhost".equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || "localhost".equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("X-Forwarded-For");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || "localhost".equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("X-Real-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || "localhost".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddress().getAddress().getHostAddress();
}
} catch (Exception e) {
log.error("RequestUtil.getIpAddr 获取请求真实ip 发生异常,异常信息为 - {} ", e);
throw new ...;
}
return ip;
}
}
六、获取request对象
原项目中使用的是spring-webmvc,需要获取IP打点。之前使用RequestContextHolder.getRequestAttributes()获取,替换为spring-webflux后,报空指针异常。
提供简单的方法解决,在controller层的方法入参中增加org.springframework.http.server.reactive.ServerHttpRequest
@PostMapping("/loginForOtherSys")
public Map loginForOtherSys(@RequestBody @Valid LoginOtherSysUserVO loginOtherSysUserVO, ServerHttpRequest request) {
...
}
标签:spring,org,request,springframework,equalsIgnoreCase,ip,import,gateway,cloud
From: https://www.cnblogs.com/zhuimu22/p/17037709.html