- 在spring-cloud-alibaba项目中像创建gateway-example模块
- 引入gateway开发包
<?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>spring-cloud-alibaba</artifactId>
<groupId>spring-cloud-alibaba</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gateway-example</artifactId>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.cloud.alibaba.GatewayApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
- bootstrap.yml
spring:
application:
name: gateway-example
profiles:
active: dev
main:
allow-bean-definition-overriding: true
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 101.37.152.195:8848
config:
server-addr: 101.37.152.195:8848
# 配置文件格式
file-extension: yml
# 共享配置
shared-dataids: application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
- nacos配置
Data ID: gateway-example.yml
Group:DEFAULT_GROUP
配置格式:YAML
配置内容:
spring:
cloud:
gateway:
filter:
remove-non-proxy-headers:
headers:
routes:
- id: producer-example
uri: lb://producer-example
predicates:
- Path=/producer/**
# StripPrefix=1,否则访问服务时会带上producer
filters:
- StripPrefix=1
server:
port: 10004
/producer/**请求 转发至producer-example服务的 /**接口
4. 配置gateway异常处理器
package com.cloud.alibaba.config.handler;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
/**
* 网关统一异常处理
*
* @author
*/
@Order(-1)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
ServerHttpResponse response = exchange.getResponse();
ResponseStatusException responseStatusException = null;
if (exchange.getResponse().isCommitted()) {
return Mono.error(ex);
}
String msg;
if (ex instanceof NotFoundException) {
msg = "服务未找到";
} else if (ex instanceof ResponseStatusException) {
responseStatusException = (ResponseStatusException) ex;
msg = responseStatusException.getMessage();
} else {
msg = "内部服务器错误";
}
log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
response.setStatusCode(HttpStatus.OK);
if (responseStatusException != null) {
ResponseStatusException finalResponseStatusException = responseStatusException;
return response.writeWith(Mono.fromSupplier(() -> getDataBuffer(response, msg, finalResponseStatusException.getStatus().value())));
} else {
return response.writeWith(Mono.fromSupplier(() -> getDataBuffer(response, msg, 500)));
}
}
private DataBuffer getDataBuffer(ServerHttpResponse response, String msg, int status) {
DataBufferFactory bufferFactory = response.bufferFactory();
Map<String, Object> map = new HashMap<>(2);
map.put("status", status);
map.put("msg", msg);
return bufferFactory.wrap(JSON.toJSONBytes(map));
}
}
- 启动类
package com.cloud.alibaba;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author 刘志强
* @date 2020/11/19 09:34
*/
@EnableDiscoveryClient
@SpringBootApplication
@Slf4j
public class GatewayApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Override
public void run(String... args) {
log.info("gateway已启动");
}
}
- 启动producer-example 和 gateway-example服务
- 访问 http://xxx.xx.xx.xx:10004/producer/getUserName
- 关闭producer-example 访问 http://xxx.xx.xx.xx:10004/producer/getUserName 观察响应