当前位置:网站首页>Gateway service gateway
Gateway service gateway
2022-06-30 23:35:00 【RB_ VER】
Concept
spring cloud A very important component of the whole family bucket is the gateway , stay 1.x It's used in all versions Zuul gateway , stay 2.x In the version ,zuul The upgrade of has been ticket hopping ,spring cloud Finally, I developed a gateway to replace zuul, That's it spring cloud gateway.
spring cloud gateway yes spring cloud A brand new project , be based on spring 5.0+spring boot 2.0 and project reactor Such as technology development gateway , It aims to provide a simple and effective unified approach to microservice architecture API Routing management .
spring cloud gateway As spring cloud Gateways in an ecosystem , The goal is to replace zuul, stay spring cloud 2.0 In the above version , There is no new version of zuul 2.0 The latest performance version above is integrated , Still in use zuul 1.x Not reactor The old version of the pattern . In order to improve the performance of the gateway ,spring cloud gateway Is based on webflux Framework implementation , and webflux The bottom layer of the framework uses high-performance reactor Mode communication framework netty.
spring cloud gateway The goal is to provide a unified routing method based on filter The chain approach provides the gateway's basic functionality , for example : Security 、 monitor / indicators 、 Current limiting .
function : Reverse proxy 、 authentication 、 flow control 、 Fuse 、 Log monitoring .

spring cloud gateway Has the following characteristics :
- be based on spring framework 5,project reactor and spring boot 2.0 Build ;
- Dynamic routing : Can match any request property ;
- Routing can be specified predicate( Assertion ) and filter( filter );
- Integrate hystrix The breaker function of ;
- Integrate spring cloud Service discovery capabilities ;
- Easy to write predicate and filter;
- Request current limiting function ;
- Support path rewriting .
Conventional web frame , for instance :struts2,springmvc And so on servlet API And servlet Container based . however , stay servlet 3.x Then there's asynchronous non blocking support . and webflux It's a typical nonblocking asynchronous framework , Its core is based on reactor Correlation API Realized . Compared with the traditional web Frame speaking , It can run on things like netty、undertow And support servlet 3.1 On the container . Non-blocking type + Functional programming .
spring webflux yes spring 5.0 The introduction of a new responsive framework , The difference in springmvc, It doesn't have to rely on servlet API, It's completely asynchronous and non blocking , And based on reactor To implement responsive flow specifications .
gateway The core concept
route( route )
Routing is the basic module of building a gateway , It consists of ID, The goal is URI, A series of assertions and filters , If the assertion is true Then match the route .
predicate( Assertion )
Reference resources Java 8 Of java.util.function.Predicate, Developers can match HTTP Everything in the request ( For example, request header or request parameter ), If the request matches the assertion, route it .
filter( Filter )
refer to spring In the frame GatewayFilter Example , Use filters , Requests can be modified before or after they are routed .

web request , Through some matching conditions , Go to the real service node . And before and after this forwarding process , Do some fine control .predicate Is the matching condition ;filter It can be understood as an interceptor , With these two elements , Plus the goal uri, You can implement a specific route .
Build a microservice gateway
establish cloud-gateway-gateway9527 modular
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud2022</artifactId>
<groupId>com.qrxqrx.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-gateway-gateway9527</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.qrxqrx.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
application.yml
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
routes:
- id: payment_route # The routing id, There are no fixed rules, but only one is required , Suggested service name
uri: http://localhost:8001 # The routing address of the service after matching
predicates:
- Path=/payment/get/** # Assertion , Route by path matching
- id: payment_route2 # The routing id, There are no fixed rules, but only one is required , Suggested service name
uri: http://localhost:8001 # The routing address of the service after matching
predicates:
- Path=/payment/lb/** # Assertion , Route by path matching
eureka:
instance:
hostname: cloud-gateway-service
client:
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eureka
GatewayMain9527
package com.qrxqrx.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class GatewayMain9527 {
public static void main(String[] args) {
SpringApplication.run(GatewayMain9527.class,args);
}
}
Gateway Two configuration modes of gateway routing
- stay yml Configuration in file ( Above )
- Inject... Into the code RouteLocator Of bean
GatewayConfig
package com.qrxqrx.springcloud.config;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes().route("path_route_qrx1",
r -> r.path("/payment/get/**")
.uri("http://localhost:8001")).build();
}
}
Configure dynamic routing
By default ,gateway According to the list of micro services registered in the registry , Create a dynamic route with the microservice name as the path for forwarding , So as to realize the function of dynamic routing .
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true # Turn on dynamic routing
routes:
- id: payment_route # The routing id, There are no fixed rules, but only one is required , Suggested service name
# uri: http://localhost:8001 # The routing address of the service after matching
uri: lb://cloud-payment-service # Dynamic routing
predicates:
- Path=/payment/get/** # Assertion , Route by path matching
- id: payment_route2 # The routing id, There are no fixed rules, but only one is required , Suggested service name
# uri: http://localhost:8001 # The routing address of the service after matching
uri: lb://cloud-payment-service # Dynamic routing
predicates:
- Path=/payment/lb/** # Assertion , Route by path matching
eureka:
instance:
hostname: cloud-gateway-service
client:
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eureka
Predicate Use

spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true # Turn on dynamic routing
routes:
- id: payment_route # The routing id, There are no fixed rules, but only one is required , Suggested service name
# uri: http://localhost:8001 # The routing address of the service after matching
uri: lb://cloud-payment-service # Dynamic routing
predicates:
- Path=/payment/get/** # Assertion , Route by path matching
# ZonedDateTime zbj = ZonedDateTime.now();
# System.out.println(zbj);
- After=2022-06-30T16:17:33.876+08:00[Asia/Shanghai] # Only after this time can access be effective
- Cookie=name,qrx
# Cookie Route Predicate Two parameters are required , One is cookie name, One is a regular expression .
# The routing rules are retrieved by the corresponding cookie name The value matches the regular expression , If there is a match, the route is executed , If there is no match, it is not executed .
# test :curl http://localhost:9527/payment/lb --cookie "username=zzyy"
- Header=X-Request-Id,\d+
# Two parameters : An attribute name and a regular expression , If the attribute value matches, execute
# test :curl http://localhost:9527/payment/lb --H "X-Request-Id:123"
- Host=www.qrxqrx.com
# test :curl http://localhost:9527/payment/lb --H "Host:www.qrxqrx.com"
- Method=GET
- Query=username,qrx
# test :curl http://localhost:9527/payment/lb?username=qrx
Filter Use
Routing filters can be used to modify incoming HTTP Requested and returned HTTP Respond to , Routing filters can only specify routes to use .
By life cycle :
- pre
- post
By category : - GatewayFilter
- GlobalFilter
spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true # Turn on dynamic routing
routes:
- id: payment_route # The routing id, There are no fixed rules, but only one is required , Suggested service name
# uri: http://localhost:8001 # The routing address of the service after matching
uri: lb://cloud-payment-service # Dynamic routing
predicates:
- Path=/payment/get/** # Assertion , Route by path matching
- id: payment_route2 # The routing id, There are no fixed rules, but only one is required , Suggested service name
# uri: http://localhost:8001 # The routing address of the service after matching
uri: lb://cloud-payment-service # Dynamic routing
predicates:
- Path=/payment/lb/** # Assertion , Route by path matching
filters:
- AddRequestParameter=X-Request-Id,1024 # The filter factory adds a pair of request headers to the matching request header , The name is X-Request-Id, The value is 1024
Custom filter
package com.qrxqrx.springcloud.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Date;
@Component
@Slf4j
public class MyLogGatewayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("----come in MyLogGatewayFilter----"+new Date());
String uname = exchange.getRequest().getQueryParams().getFirst("uname");
if (uname == null) {
log.info("++++username is null! illegal!");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
test :http://localhost:9527/payment/lb?uname=xxx
边栏推荐
- Fund customer service
- 206页上海BIM技术应用与发展报告2021
- 深入理解 Jetpack Compose 内核:SlotTable 系统
- 基金管理人公司治理和风险管理
- When we look at the industrial Internet, we always look at it from the opposite of the consumer Internet
- Sm2246en+ SanDisk 15131
- Reason why wechat payment wxpaypubhelper V3 callback XML is empty
- How do it outsourcing resident personnel position their pain points?
- Understand target detection in one article: r-cnn, fast r-cnn, fast r-cnn, Yolo, SSD "suggestions collection"
- Query points in MATLAB Delaunay triangulation
猜你喜欢

shell 同时执行多任务下载视频

1. crawler's beautifulsoup parsing library & online parsing image verification code

6-1 exploit -ftp exploit
![[leetcode] [SQL] notes](/img/8d/160a03b9176b8ccd8d52f59d4bb47f.png)
[leetcode] [SQL] notes

HP 惠普笔记本电脑 禁用触摸板 在插入鼠标后

How does the VR cloud exhibition hall bring vitality to offline entities? What are the functions?

One revolution, two forces and three links: the "carbon reduction" road map behind the industrial energy efficiency improvement action plan

Fh6908a negative pole turn off synchronous rectification analog low voltage drop diode control IC chip tsot23-6 ultra low power rectifier 1W power consumption < 100ua static replacement mp6908

Solve arm_ release_ ver of this libmali is ‘g2p0-01eac0‘,rk_ so_ Ver is' 4 ', libgl1 mesa dev will not be installed, and there are unsatisfied dependencies

Solution to the conflict between unique index and logical deletion
随机推荐
1175. 質數排列 / 劍指 Offer II 104. 排列的數目
In 2022, the latest JCR officially released the list of the latest global impact factors (top 600)
Fund sales code of conduct and information management
Solution to the conflict between unique index and logical deletion
leetcode 474. Ones and zeroes (medium)
hot-fix、cherry-pick怎么提
Fh6908a negative pole turn off synchronous rectification analog low voltage drop diode control IC chip tsot23-6 ultra low power rectifier 1W power consumption < 100ua static replacement mp6908
Ms17-010 Eternal Blue vulnerability of MSF
Fastjson V2 simple user manual
The college entrance examination in 2022 is over. Does anyone really think programmers don't need to study after work?
CNN classic network model details -lenet-5 (pytorch Implementation)
Ctfshow permission maintenance
Youfu network hybrid cloud accelerates enterprise digital transformation and upgrading
异步過渡方案—Generator
机器学习编译入门课程学习笔记第二讲 张量程序抽象
Dell r720 server installation network card Broadcom 5720 driver
Detailed explanation of conv2d of pytorch
需求评审,测试人员应该发挥怎样的价值?两分钟让你不再懵逼
New trends of China's national tide development in 2022
电商秒杀系统