I. Introduction
(1) Requirements: The microservices in the server are only allowed to be called by internal personnel or intranet personnel, and access by external network personnel is denied.
(2) How to realize the demand? gateway
(3) Functions of the gateway
- Identity authentication and permission verification
- Service routing, load balancing
- request throttling
(4) Technical realization of the gateway
Spring Cloud provides two gateway implementations:
- Spring Cloud Gateway , based on WebFlux provided in Spring 5, is an implementation of responsive programming with better performance.
- zuul —— Based on Servlet implementation, it belongs to blocking programming.
Second, the basic use of Gateway
(1) Building a gateway service
1. Common new modules, introduce SpringCloudGateway dependencies and nacos service discovery dependencies
<!--网关依赖-->
<dependency>
<groupId>org.springframework.cloud</gourpId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos服务发现依赖-->
<dependency>
<groupId>com.alibaba.cloud</gourpId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2. Create a gateway service
@SpringBootApplication
public class GatewayApplication{
public static void main(String[] args) {
SpringApplicaiton.run(GatewayApplication.class,args);
}
}
3. Implement gateway routing
Configure routing configuration
server:
port: 10010 #网关端口
spring:
application:
name: gateway #服务名称
cloud:
nacos:
server-addr: localhost:8848 #nacos地址
gateway:
routes: #网关路由配置
- id: user-service #路由id,自定义只要唯一即可
# uri: http://127.0.0.1:8081 #路由的目标地址 http是固定地址
uri: lb://userservice #路由目标地址,lb是负载均衡,后面是服务名称
predicates: # 路由断言,判断请求是否符合路由规则的条件
- Path=/user/** # 这个是按照路径匹配,只要以 /user/ 开头就符合要求
Summarize:
- How to configure the gateway
- Introduce gateway dependency, nacos service discovery dependency
- Configure application, including basic service information, nacos address, routing
- routing configuration
- id : the unique identifier of the route
- uri : routing destination, supports both lb and http
- predicates : Routing assertion, to judge whether the request meets the requirements and forward it to the routing destination
- filters : route filters, processing requests and responses
Three, the assertion factory Route Predicate Factory
(1) The purpose of using the assertion factory
The assertion rules in the configuration file are only strings, and these strings will eventually be read and processed by the Predicate Factory , turning them into conditions for routing judgments.
(2) The basic assertion factory provided by Spring
name | illustrate | example |
---|---|---|
After |
is a request after a certain point in time
|
- After=2037-01-20T17:42:47.489-07:00[America/denver]
|
Before |
is a request before a certain point in time
|
- Before=2037-01-20T17:42:47.489-07:00[America/denver]
|
Between |
is a request before some two time points
|
- Between=2037-01-20T17:42:47.489-07:00[America/denver], 2099-01-20T17:42:47.489-07:00[America/denver]
|
Cookie |
Requests must contain certain cookies
|
- Cookie=chocolate, ch.p
|
Header |
The request must contain certain Headers
|
- Header=X-Request-id,\d+
|
Host |
The request must be to access a certain host (domain name)
|
- Host=**.somehost.org,**.anotherhost.org
|
Method |
The request method must be specified
|
- Method=GET,POST
|
Path (commonly used) |
The request path must conform to the specified rules
|
- Path= /red/(segment),/blue/**
|
Query |
The request parameters must contain the specified parameters
|
- Query=name.jack or -Query=name
|
RemoteAddr (commonly used) |
Requester IP must be in the specified range
|
- RemoteAddr=192.168.1.1/24
|
Weight |
weight processing
|
(3) Summary
- What is the role of PredicateFactory?
Read user-defined assertion conditions and make judgments on requests - What does Path=user/** mean?
Paths starting with /user/ are considered to be in compliance
4. Filter factory
(1) Route filter GatewayFilter
GatewayFilter is a filter in the gateway, which can process the request entering the gateway and the response returned by the microservice.
(2) Commonly used filter factories
Spring provides 31 different route filter factories.
Common filter factory list
name | illustrate |
---|---|
AddRequestHeader | Add a request header to the current request |
RemoveRequestHeader | Remove a request header from the request |
AddResponseHeader | Add a response header to the response result |
RemoveResponseHeader | Remove a response header from the response result |
RequestRateLimiter | Limit request traffic |
(3) Summary
- What does the filter do?
- Process the routed request or response
- The filter configured under the route only takes effect for the request of the current route
- What is the role of defaultFilters?
- A filter that applies to all routes
5. Global filter
(1) Global Filter GlobalFilter
The role of the global filter is to process all requests and microservice responses entering the gateway, which is consistent with the role of GatewayFilter.
What is the difference between a global filter and a Gateway?
GatewayFilter is defined through configuration, and the processing logic is fixed.
The logic of GlobalFilter is implemented through code.
(2) Realize GlobalFilter
This is done by implementing a GlobalFilter.
public interface GlobalFilter{
/**
* 处理当前请求,有必要的话通过{@link GatewayFilterChain}将请求交给下一个过滤器处理
* @param exchange 请求上下文,里面可以获取Request、Response等信息
* @param chain 用来把请求委托给下一个过滤器
* @return {@code Mono<Void>} 返回标识当前过滤器业务结束
* */
Mono<Void> filter(ServerWevExchange exchange, GatewayFilterChain chain);
}
(3) Example
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
@Override
Mono<Void> filter(ServerWevExchange exchange, GatewayFilterChain chain){
//1、获取请求参数
ServerHttpRequest = exchange.getRequest();
MultiValueMap<String,String> params = request.getQueryParams();
//2、获取参数中的 authorization 参数
String auth = params.get("authorization "):
//3、判断参数值是否为admin
if("admin".equals(auth)){
//4、若是则放行
return chain.filter(exchange);
}
//5、若否则设置状态码并拦截
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
(4) Summary
- What does the global filter do?
A filter that works on all routes, and can customize the processing logic - Steps to implement a global filter?
- Implement the GlobalFilter interface
- Add @Order annotation or implement Ordered interface
- write processing logic
6. Execution order of filters
Gateway filters learned so far: current route filter , DefaultFilter , GlobalFilter
(1) The reason why the filter can be sorted and executed
All filters will be adapted through AddRequestHeaderGatewayFilterFactory class, the result of adaptation is GatewayFilter, and all filters can be sorted and executed.
(2) Filter sorting rules
- Each filter must specify an order value of int type, the smaller the order value, the higher the priority, and the higher the execution order
- GlobalFilter specifies the order value by implementing the ordered interface or adding an Order annotation.
- The order of routing filter and defaultFilter is specified by Spring, and the order of declaration is incremented from 1 by default.
- When the filter order values are the same, execute in the order of DefaultFilter > Route Filter > GlobalFilter .
7. Cross-domain issues
(1) What is the cross-domain problem?
Inconsistent domain names are cross-domain, mainly including:
- The domain name is different , www.taobao.com - www.taobao.org or www.jd.com - miaosha.jd.com.
- The ports are different , localhost:8080 - localhost:8081.
(2) Causes of cross-domain problems
The browser prohibits cross-domain Ajax requests between the request initiator and the server , and the request is intercepted by the browser.
(3) Solution: CORS
Configure the CORS scheme
spring:
cloud:
gateway:
globalcors: #全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: #允许地址请求
- “http://localhost:8090”
- "http://www.leyou.com"
allowedMethods: # 允许跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowedCredentials: true # 是否允许携带Cookie
maxAge: 360000 # 跨域检测的有效期