一、前言
生产环境中所有的请求入口都是统一的,一般用Nginx->Gateway。微服务之间相互调用是走内网。Gateway是所有服务对外的入口。在Gateway上可以做权限的认证和拦截。
二、Maven依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.llh</groupId>
<artifactId>parent</artifactId>
<version>1.0.0</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gateway</artifactId>
<version>1.0.0</version>
<name>gateway</name>
<description>gateway description</description>
<packaging>jar</packaging>
<dependencies>
<!--服务注册与发现-->
<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>
<!--负载均衡器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
</dependencies>
</project>
三、配置文件 application.properties
server.port=20000
# 应用名称
spring.application.name=gateway
# nacos服务注册相关
spring.cloud.nacos.discovery.server-addr=http://localhost:8848
spring.cloud.nacos.discovery.namespace=83e9d384-d49e-4f40-84bf-c25612883dcc
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# 网关相关
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id=true
spring.cloud.gateway.routes[0].id=consumer
spring.cloud.gateway.routes[0].uri=lb://consumer
spring.cloud.gateway.routes[0].predicates[0]=Path=/order/**
spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1
- 这里做了路由更改,所有/order开头的接口会路由到
consumer
服务上的接口。
四、自定义Filter
MyFilter
类
package com.llh.gateway;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
/**
* @author 小虎哥的技术博客
*/
@Component
public class MyFilter implements WebFilter{
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String path = request.getPath().toString();
// 打印请求路径,生产环境可以在此做一些权限认证等
System.out.println(path);
return chain.filter(exchange);
}
}
- 所有的请求都会通过这个拦截器,这里只是打印了一下请求路径,生产环境可以在此做一些权限认证等
五、运行
请求网关的接口都会被转发到具体的服务中
请求接口: 网关ip:网关port/服务名/服务内部接口
如 http://localhost:20000/consumer/consumer/buy/1/1
因为做了路由的转发
http://localhost:20000/order/consumer/buy/1/1
就等于
http://localhost:20000/consumer/consumer/buy/1/1
六、结语
源码地址:https://github.com/tigerleeli/xiaohuge-blog/tree/master/spring-cloud-alibaba-gateway
同步微信公众号:小虎哥的技术博客