首先要创建一个新的springboot的项目,作为gateway的项目
1.引入pom.xml中的依赖( SpringCloud gateway基于webflux实现的,不是基于SpringBoot-web,所以应该删除spring-boot-starter-web依赖 )
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<!-- nacos整合服务注册与发现-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.2.2.RELEASE</version>
</dependency>
</dependencies>
2.配置application.yml
server:
port: 80
####服务网关名称
spring:
application:
name: pitch-gateway
cloud:
gateway:
####解决跨域的问题
globalcors:
corsConfigurations:
'[/**]':
allowedHeaders:"*"
allowedOrigins: "http://www.xinyues.com"
allowedMethods:
- GET
#超时设置
httpclient:
connect-timeout: 5000 #毫秒
response-timeout: 5s
discovery:
locator:
####允许从注册中心获取地址
enabled: true
routes:
###路由id 自定义唯一,这个没有什么保证唯一就行了
- id: pitch
####pitch-member为会员服务的名称,这个可以用lb这个后面跟微服务的名称会用到负载均衡,如果用http ####不会进行负责均衡
uri: lb://pitch-member/
####这个是gateway提供的一些过滤器
filters:
- StripPrefix=1
###路由匹配规则 表示当客户端访问http://ip:80/member/**地址时, gateway就会转发到pitch-member会员服务的具体地址
predicates:
- Path=/member/**
nacos:
discovery:
###将网关服务注册到nacos
server-addr: 127.0.0.1:8848
enabled: true
3.就是根据业务进行一些自定义的过滤规则了,自定义过滤规则的时候要实现globalfilter,有选择的实现ordered
例子:
①实现权限管理,日志管理 参考
②使用全局过滤器解决跨域问题
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
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;
@Component
public class CrossOriginFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 允许跨域请求
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
HttpHeaders headers = response.getHeaders();
//在生产环境上最好指定域名,以免产生跨域安全问题
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
return chain.filter(exchange);
}
}
gateway 的配置可以在数据库中进行配置,可参考https://blog.csdn.net/xiaobo5264063/article/details/105205974