当前位置:网站首页>Gateway service gateway
Gateway service gateway
2022-06-10 17:33:00 【itmkyuan】
Why do I need a gateway ?
Gateway function :
- Authentication and authority verification
- Service routing 、 Load balancing
- Request current limiting

stay SpringCloud The implementation of gateway in includes two methods :
- gateway
- 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 .
Steps of building gateway service :
1. Create a new module, introduce SpringCloudGateway Dependence and nacos Dependency of service discovery :
<!-- 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>
2. Write routing configuration and nacos Address
server:
port: 10010 # Gateway port
spring:
application:
name: gateway # The service name
cloud:
nacos:
server-addr: localhost:8001 # nacos Address
discovery:
namespace: c072b17e-a5a6-4c23-aff3-aa83749eefa0
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
- id: order-service
uri: lb://orderservice
predicates:
- Path=/order/**
Build gateway service :
Gateway building steps :
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
Route assertion factory Route Predicate Factory
The assertion rules we write in the configuration file are just strings , These strings will be Predicate Factory Read and process , The condition for changing to routing judgment
for example Path=/user/** Is to match according to the path , This rule is made by
org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory Class to handle
Spring Provides 11 Species basic Predicate factory :
PredicateFactory What is the role of
Read user-defined assertion conditions , Judge the request
Path=/user/** What does it mean
The path is user The beginning is considered to be consistent
Routing filter GatewayFilter
GatewayFilter It is a filter provided in the gateway , Can enter Gateway request and The response returned by the microservice Do the processing :
Spring Provides 31 There are different routing filter factories . for example :
Give everyone access userservice Add a request header to your request :Truth=itcast is freaking awesome!
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, Itcast is freaking awesome! # Add request header
If you want to be effective for all routes , The filter factory can be written to default Next . The format is as follows :
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://userservice
predicates:
- Path=/user/**
default-filters: # Default filter
- AddRequestHeader=Truth, Itcast is freaking awesome!
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
defaultFilters What is the role of ?
① Filters in effect for all routes
Global filter
The global filter is also used to handle all requests and microservice responses entering the gateway , And GatewayFilter It does the same thing .
The difference lies in GatewayFilter Defined by configuration , The processing logic is fixed . and GlobalFilter You need to write your own code to implement your logic .
The definition is to implement GlobalFilter Interface .
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 is authorization,
authorization Whether the parameter value is admin
If both are met, release , Otherwise intercept
Custom filter
Custom class , Realization GlobalFilter Interface , add to @Order annotation :
package cn.itcast.gateway.filters;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. Get request parameters
MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
// 2. obtain authorization Parameters
String auth = params.getFirst("authorization");
// 3. check
if ("admin".equals(auth)) {
// release
return chain.filter(exchange);
}
// 4. Intercept
// 4.1. Blocking access , Set status code
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
// 4.2. End processing
return exchange.getResponse().setComplete();
}
}
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
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 
What are the sorting rules ?
- 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 .
The detailed content , You can check the source code :
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
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
Cross domain problem handling
Cross domain : Domain name inconsistency is cross domain , It mainly includes :
Domain name is different : www.taobao.com and www.taobao.org and www.jd.com and miaosha.jd.com
Domain name is the same , Different ports :localhost:8080 and localhost8081
Cross-domain problem : browser The originator of the prohibition request and Cross domain on the server ajax request , The request is blocked by the browser
Solution :CORS
The gateway handles cross domain transactions in the same way CORS programme , 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
CORS Which parameters should be configured across domains ?
① Which domain names are allowed to cross domains ?
② Which request headers are allowed ?
③ What kind of requests are allowed ?
④ Is it allowed to use cookie?
⑤ How long is the validity period ?
Thank you for your participation
Video address :https://www.bilibili.com/video/BV1LQ4y127n4?p=35
边栏推荐
- Redis general instruction
- 【玩转华为云】鲲鹏DevKit迁移实战
- C#_ Serial port communication project
- Nat. Rev. Drug Discov. | Application of AI in small molecule drug discovery: an upcoming wave?
- 2022年焊工(初级)试题模拟考试平台操作
- 基于DeepFace模型设计的人脸识别软件
- Fabric.js 居中元素 ️
- 2022年G2电站锅炉司炉考试模拟100题及模拟考试
- 嘿!ONES 新星请看过来|师兄师姐说
- Nat. Rev. Drug Discov. | AI在小分子药物发现中的应用:一个即将到来的浪潮?
猜你喜欢

绘制混淆矩阵

SOA architecture / test phase interface description language transformation scheme

自定义视图:图形与图像的处理(一):使用简单图片

C#_串口通信项目

品牌难立,IPO难行,中国茶企困于“传统”?
Example analysis of SQL injection error reporting

二十多年了,安全套市场还只有杜蕾斯、冈本、杰士邦

仅需三步学会使用低代码ThingJS与森数据DIX数据对接

Only three steps are needed to learn how to use low code thingjs to connect with Sen data Dix data

Flood control and drainage monitoring automatic monitoring and telemetering terminal for flood control and drainage
随机推荐
每日一题-1287. 有序数组中出现次数超过25%的元素
Designing drugs with code: are we here yet?
Take you to a preliminary understanding of the basic mechanism of classes and objects
C#_串口通信项目
聊聊消息中间件(1),AMQP那些事儿
Example analysis of SQL injection error reporting
Intelligent scenic spot video monitoring 5g intelligent light pole gateway networking integrated pole
安全感
嘿!ONES 新星请看过来|师兄师姐说
For more than 20 years, there are only Durex, Okamoto and jasbon in the condom market
Only three steps are needed to learn how to use low code thingjs to connect with Sen data Dix data
Swift 3pThread tool Promise Pipeline Master/Slave Serial Thread confinement Serial queue
【玩转华为云】鲲鹏DevKit迁移实战
Swing visualization plug-in jformdesigner of idea
SOA architecture / test phase interface description language transformation scheme
Eliminate if Five ways of else
C# 根据EXCEL自动生成oracle建表语句
C#_ Serial port communication project
Richard Behrman, the founder of dynamic planning
Fabric. Keep the original level when JS element is selected