当前位置:网站首页>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
边栏推荐
- 几个对程序员的误解,害人不浅!
- 开源项目 PM 浅谈如何设计官网
- Facebook AI | learning reverse folding from millions of prediction structures
- Only three steps are needed to learn how to use low code thingjs to connect with Sen data Dix data
- Daily question -1287 Elements that appear more than 25% in an ordered array
- Importerror: libgl. so. 1: cannot open shared object file: no such file or directory
- Redis general instruction
- Fabric.js 精简输出的JSON
- Snabbdom 虚拟 dom(一)
- com.netflix.client.ClientException: Load balancer does not have available server for client: userser
猜你喜欢

The children in the deep mountains are seeing the stars farther away

C#_ Serial port communication project

Nacos配置管理

2022年茶艺师(中级)操作证考试题库及模拟考试

Numpy learning notes

单片机底层通信协议① —— 同步和异步、并行和串行、全双工和半双工以及单工、电平信号和差分信号

“挽弓当挽强,用箭当用长”,曼孚科技为数据服务行业开启新赛道

Solve the problem that idea is stuck in opening a project

Eliminate if Five ways of else

为什么 0.1+0.2=0.30000000000000004
随机推荐
当v-if和v-for需要同时使用的时候
[BSP video tutorial] BSP video tutorial issue 17: single chip microcomputer bootloader topic, startup, jump configuration and various usage of debugging and downloading (2022-06-10)
VBA judge whether the file exists and ask for the idea of file backup
简易的站点备份 Shell 脚本
Online communication skill network: a sparse model for solving multi task and multi-modal problems (Qingyuan talk, issue 19, tangduyu)
Nat. Rev. Drug Discov. | Application of AI in small molecule drug discovery: an upcoming wave?
2022年茶艺师(中级)操作证考试题库及模拟考试
Internet enterprises and chips
成立1年便成独角兽,腾讯滴滴做「靠山」,今年新晋的独角兽不简单
Redis general instruction
Web3 is the most complete money making secret script. Just read this one
嘿!ONES 新星请看过来|师兄师姐说
What should be done to improve the service level of the park and optimize the business environment
Swift 3pThread tool Promise Pipeline Master/Slave Serial Thread confinement Serial queue
如何运行plink软件--三种方法
Fabric. JS centered element
What is the highest compound interest insurance product? How much does it cost a year?
李飞飞:我更像物理学界的科学家,而不是工程师|深度学习崛起十年
How MySQL modifies field type and field length
2022年G2电站锅炉司炉考试模拟100题及模拟考试