上一篇博客写了nacos的部分,今天来记录一下gateway的使用过程,在已经有了注册中心的基础上,再去添加gateway就已经很简单了。
依赖如下:
<dependencies>
<!-- nacos客户端依赖包 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--网关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
只需要nacos客户端和gateway的依赖
注意:这里不需要spring-boot-starter-web的依赖!添加了之后还有可能会有冲突。
启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// 开启网关
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
yml配置文件
#配置网关端口号
server:
port: 8000
spring:
application:
#注册进nacos的名字
name: gateway-server
cloud:
nacos:
discovery:
server-addr: localhost:8848
gateway: #gateway网关配置
routes: #路由配置
- id: DEVP-Auth #路由标识,必须唯一
uri: lb://DEVP-Auth #路由的目标地址
predicates: #路由断言,判断请求是否符合规则
#路径断言,判断路径是否是以某些字段开头,如果是则符合。以逗号隔开
- Path=/api-server/verify,/api-server/login/check,/api-server/login,/api-server/logout
- id: FCV-ApiServer
uri: lb://FCV-ApiServer
predicates:
- Path=/api-server/**
globalcors: #全局的跨域处理
cors-configurations:
'[/**]':
allowedOrigins: #允许哪些网站的跨域请求
- "http://localhost:18191"
- "http://localhost:8080"
- "http://localhost:8081"
# - "http://localhost:8000"
allowedMethods: #允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" #允许在请求中携带的头信息
allowCredentials: true #允许携带cookie
maxAge: 360000 #这次跨域检测的有效期
这样最简单的网关配置就搞定了!
当然我们可以根据自己的情况去添加拦截器之类的内容,如下:
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
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.nio.charset.StandardCharsets;
/**
* @author 刘朋
* <br/>date 2021-11-08
*/
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange);
/*
String authorization = exchange.getRequest().getQueryParams().getFirst("authorization");
if("admin".equals(authorization)){
return chain.filter(exchange);
}
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
byte[] bits = "鉴权失败".getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bits);
//指定编码,否则在浏览器中会中文乱码
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
return response.writeWith(Mono.just(buffer));*/
}
}