当前位置:网站首页>Basic use of gateway
Basic use of gateway
2022-07-26 22:53:00 【Charming】
Spring Cloud Gateway yes Spring Cloud A brand new project , The project is based on Spring 5.0,Spring Boot 2.0 and Project Reactor Gateway developed by responsive programming and event flow technology , It aims to provide a simple and effective unified approach to microservice architecture API Routing management .
List of articles
- 1. Why do I need a gateway
- 2. Technical implementation of gateway
- 3. Summary :
- 4. Build gateway service
- 5. Summary
- 6. Route assertion factory Route Predicate Factory
- 7. Summary
- 8. Routing filter GatewayFilter
- 9. Request header filter
- 10. Default filter
- 11. Summary
- 12. Global filter GlobalFilter
- 13. Summary
- 14. Filter execution order
- 15. Summary
- 16. Cross domain problem handling
1. Why do I need a gateway
Gateway function :
- Authentication and authority verification
- Service routing 、 Load balancing
- Request current limiting

2. Technical implementation of gateway
- stay SpringCloud The implementation of gateway in includes two methods :
1、gateway
2、zuul - Zuul Is based on Servlet The implementation of the , It belongs to blocking programming . and SpringCloudGateway Is based on Spring5 Provided in WebFlux, It belongs to the implementation of responsive programming , Better performance .
3. Summary :
The function of gateway :
1、 Authenticate user requests 、 Permission to check
2、 Route user requests to microservices , And load balancing
3、 Limit the current of user requests
Access control : The gateway acts as a microservice portal , You need to verify whether the user is qualified to request , If not, intercept .
Routing and load balancing : All requests must go through first gateway, But the gateway doesn't handle business , But according to some rule , Forward the request to a micro service , This process is called routing . Of course, when there are multiple target services for routing , You also need to do load balancing .
Current limiting : When the request traffic is too high , In the gateway, the request is released at a speed acceptable to obscene microservices , Avoid excessive service pressure .
4. Build gateway service
Steps of setting up gateway service :
- Create a new module, introduce Spring Cloud Gateway Dependence and Nacos Service discovery depends on
<!-- gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos Service discovery depends on -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
- Write basic configuration and routing rules and nacos Address
server:
port: 10010 # Gateway port
spring:
application:
name: gateway # The service name
cloud:
nacos:
server-addr: 47.107.53.146:8848 # nacos Address
gateway:
routes: # Gateway routing configuration
- id: user-service # route id, Customize , As long as it's the only one
# uri: http://127.0.0.1:8081 # The destination address of the route http It's a fixed address
uri: lb://userservice # The destination address of the route lb It's load balancing , Followed by the service name
predicates: # Route assertion , That is, judge whether the request meets the conditions of routing rules
- Path=/user/** # This is matched according to the path , As long as /user/ Meet the requirements at the beginning
- Will conform to
PathAll requests of the rules , All agents arrive aturiThe address specified by the parameter - In this case , take
/user/**Initial request , Proxy tolb://userservice,lbIt's load balancing , Pull the service list according to the service name , Load balancing . - Flow chart of gateway routing , The whole access process is as follows :

- Restart test :
Restart gateway , visithttp://localhost:10010/user/1when , accord with/user/**The rules , Request forwarding touri:http://userservice/user/1, Got the result :
- visit
http://localhost:10010/order/101, accord with/order/**The rules , Request forwarding touri:http://orderservice/order/101, Get the results :
5. Summary
1、 Create project , introduce nacos Service discovery and gateway rely on
2、 To configure application.yml, Including basic service information 、nacos Address 、 route
- Routing configuration includes :
1、 route id: The unique identifier of the route
2、 Routing destination (uri): The destination address of the route ,http Represents a fixed address ,lb Represents load balancing based on service name
3、 Route assertion (predicates): Rules for judging routing ,
4、 Routing filter (filters): To process a request or response
6. Route assertion factory Route Predicate Factory
Gateway routing can be configured as follows :
- route id: Route unique identification
uri: Route destination , SupportlbandhttpTwo kinds ofpredicates: Route assertion , Determine whether the request meets the requirements , If yes, it will be forwarded to the routing destinationfilters: Routing filter , Process a request or response
- The assertion rules written in the configuration file are just strings , These strings will be
Predicate FactoryRead and process , The condition for changing to routing judgment - for example
Path=/user/**Is to match according to the path , This rule is made byorg.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactoryClass to handle - Assertion factories like this are SpringCloudGateway There are more than a dozen
Spring Provides 11 Species basic Predicate factory :
Such as : hold orderservice Set at 2023 Requests after , Obviously, it does not meet the requirements , newspaper 404 error


Assertions can be made according to requirements Predicate Make relevant settings , Official document :
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories
7. Summary
PredicateFactoryWhat is the role of ?
Read user-defined assertion conditions , Make a judgment on the requestPath=/user/**What does it mean ?
The path is/userThe beginning is considered to be consistent
8. Routing filter GatewayFilter
GatewayFilterIt is a filter provided in the gateway , You can process the request to enter the gateway and the response returned by the microservice :
Spring Provides 31 There are different routing filter factories . for example :
| name | explain |
|---|---|
| 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 the requested traffic |
- Official website :https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gatewayfilter-factories
9. Request header filter
Let's say AddRequestHeader For example to explain :
- Give everyone access
userserviceAdd a request header to your request :Truth=Just Do It! - Realization way : stay gateway Revision in China application.yml file , to userservice Add filter for route :
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://userservice
predicates:
- Path=/user/**
filters: # filter
- AddRequestHeader=Truth, Just Do It! # Add request header
stay userservice Under the UserController Add the printed request header information under

restart userservice, After visiting, you can see :

The current filter is written in userservice Under route , So just access userservice Your request is valid
10. Default filter
- If you want to be effective for all routes , The filter factory can be written to
defaultNext . The format is as follows :
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://userservice
predicates:
- Path=/user/**
default-filters: # Default filter
- AddRequestHeader=Truth, Just Do It!

11. Summary
- What is the function of the filter ?
① Process the routed request or response , For example, add request headers
② The filter configured under the route is only effective for the requests of the current route
defaultFiltersWhat is the role of ?
① Filters in effect for all routes
12. Global filter GlobalFilter
- The global filter is also used to handle all requests and microservice responses entering the gateway , And
GatewayFilterIt does the same thing . - The difference lies in
GatewayFilterDefined by configuration , The processing logic is fixed . andGlobalFilterYou need to write your own code to implement your logic . - The definition is to implement
GlobalFilterInterface .
public interface GlobalFilter {
/** * Process the current request , If necessary, through {@link GatewayFilterChain} Pass the request to the next filter * * @param exchange Request context , You can get Request、Response Etc * @param chain Used to delegate the request to the next filter * @return {@code Mono<Void>} Return to indicate the end of the current filter business */
Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);
}
Define global filters , Intercept and determine the user's identity
demand : Define global filters , Intercept request , Judge whether the requested parameters meet the following conditions :
Whether there isauthorization,
authorization Whether the parameter value is admin
If both are met, release , Otherwise interceptCustom class , Realization GlobalFilter Interface , add to @Order annotation , stay gateway Define a filter in :
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. Get request parameters
ServerHttpRequest request = exchange.getRequest();
MultiValueMap<String, String> params = request.getQueryParams();
// 2. Get... In the request parameter authorization Parameters
String auth = params.getFirst("authorization");
// 3. Judge whether the parameter is equal to admin
if ("admin".equals(auth)) {
// 4. yes , release
return chain.filter(exchange);
}
// 5. no , Intercept
// 5.1 Set status code
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
// 5.2 Intercept request
return exchange.getResponse().setComplete();
}
}
When the specified slave parameter is not brought when accessing the service , The set status code will be reported 401


With parameters, you can normally access :

13. Summary
- What is the role of the global filter ?
Filters in effect for all routes , And you can customize the processing logic - Steps to implement the global filter ?
① Realization GlobalFilter Interface
② add to @Order To annotate or implement Ordered Interface
③ Write processing logic
14. Filter execution order
The request to enter the gateway will encounter three types of filters : Filter for the current route 、DefaultFilter、GlobalFilter
After request routing , The current route filter and DefaultFilter、GlobalFilter, Merge into a filter chain ( aggregate ) in , After sorting, execute each filter in turn

Each filter must specify a int Type of order value ,order The smaller the value. , The higher the priority , The higher the order of execution .
GlobalFilter By implementing Ordered Interface , Or add @Order Note to specify order value , It's up to us to designate
Routing filters and defaultFilter Of order from Spring Appoint , The default is from... In the order of declaration 1 Increasing .
When the filter order When the value is the same , According to defaultFilter > Routing filter > GlobalFilter Sequential execution .
You can refer to the source code of the following classes to view :
org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator
#getFilters() The method is to load defaultFilters, Then load a route Of filters, Then merge .
org.springframework.cloud.gateway.handler.FilteringWebHandler
#handle() Method loads the global filter , Combined with the previous filter, according to order Sort , Organize the filter chain
15. Summary
- Routing filter 、defaultFilter、 The execution order of the global filter ?
①order The smaller the value. , The higher the priority
② When order When the value is the same , The order is defaultFilter The first , Then there is the local routing filter , Finally, the global filter
16. Cross domain problem handling
Cross domain : Domain name inconsistency is cross domain , It mainly includes :
1、 Domain name is different : www.taobao.com and www.taobao.org and www.jd.com and miaosha.jd.com
2、 Domain name is the same , Different ports :localhost:8080 and localhost8081Cross-domain problem : The browser prohibits cross domain communication between the initiator of the request and the server ajax request , The request is blocked by the browser
Solution :
CORSThe gateway handles cross domain transactions in the same way
CORSprogramme , And it only needs simple configuration to realize :
spring:
cloud:
gateway:
# ...
globalcors: # Global cross domain processing
add-to-simple-url-handler-mapping: true # solve options The request is blocked
corsConfigurations:
'[/**]':
allowedOrigins: # Allow cross domain requests for which websites
- "http://localhost:8090"
allowedMethods: # Allowed cross domain ajax Request method of
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # Header information allowed to be carried in the request
allowCredentials: true # Is it allowed to carry cookie
maxAge: 360000 # The validity period of this cross domain detection
边栏推荐
- Parameter analysis and stone jumping board
- 继关闭苏州厂之后,欧姆龙东莞厂宣布解散,2000多人面临失业!
- SQL multi table query exercise
- 云原生微服务第一章之服务器环境说明
- Shardingsphere JDBC keyword problem
- 三星Galaxy Z可折叠产品的预告片泄露:'柔性好于平面'
- 商汤科技CEO徐立:公司估值已超70亿美元,不急于上市
- Day07 MySql知识点再总结与多表查询
- 2019生物识别论坛成功落幕:这十大看点不容错过!
- Interview: your most impressive bug, for example
猜你喜欢

Making wechat robot with go (I) sending messages

SQL二次注入详解

黑马瑞吉外卖之新增员工
![[hcip] OSPF relationship establishment](/img/19/e03fea44f2908c7b585e7a1f87c075.png)
[hcip] OSPF relationship establishment
![[MySQL] - index principle and use](/img/e1/af74ee20ebe0c6e6f5e453330cc13b.png)
[MySQL] - index principle and use

Module 8 (message queue MySQL table storing message data)

Arduino experiment I: two color lamp experiment

Recruit | PostgreSQL database R & D engineers every week, with an annual salary of 60+, high salary for famous enterprises, and challenge yourself!

三星Galaxy Z可折叠产品的预告片泄露:'柔性好于平面'

APP信息侦察&夜神模拟器Burp抓包配置
随机推荐
程序员成长第二十九篇:如何激励员工?
sql多表查询的练习
《强化学习周刊》第55期:LB-SGD、MSP-DRL & 对抗鲁棒强化学习
【HCIP】OSPF 关系建立
面试官问:JS的this指向
逆袭黑马:数据库全栈工程师(DevDBOps)培训,把最好的课程送给您!
[untitled]
"Mongodb" here are all the basic mongodb operations you want
what is a kit in qt
what is a kit in qt
华为密谋收购巴西运营商?
Which is better, caiqian school or qiniu school? Is it safe
VCs compilation and simulation process
恋爱时各个顺序整理(历时两个月详细整理)
利用Go制作微信机器人(一)发送消息
Implementation principle of semaphore in golang
每周招聘|PostgreSQL数据库研发工程师,年薪60+,名企高薪,挑战自我!
NVIDIA SMI error: NVIDIA SMI has failed because it could't communicate with the NVIDIA driver complete record
2022 latest Tibet Construction Safety Officer simulation question bank and answers
中兴通讯:5G基站在全球发货已超过5万个!