当前位置:网站首页>Gateway new generation gateway
Gateway new generation gateway
2022-07-19 08:27:00 【Illusory clarity】
1. Introduce
Cloud One of the most important components in the family bucket is the gateway , stay 1 .x It's used in all versions Zuu| gateway ;
But in 2.x In the version ,zuul Upgrade one Skip ticket , SpringCloud Finally, I developed it myself A gateway replacement Zuul, That's it SpringCloud Gateway- Sentence : gateway Is the original zuul1.x Replacement of version .
Gateway Is in Spring Built on the ecosystem API Gateway service , be based on Spring 5, Spring Boot 2 and Project Reactor Technology .
Gateway Designed to provide a simple And an effective way to API Routing , And provide some powerful filter functions , for example : Fuse 、 Current limiting 、 Retry etc. .
SpringCloud 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 .
SpringCloud 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 used Zuul 1.x Not Reactor The old version of the pattern . In order to improve the performance of the gateway ,I SpringCloud 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 Our goal is to provide - Routing Party of Formula and based on Filter The chain approach provides the gateway's basic functionality , for example : Security , monitor / indicators , And current limiting .
What can I do? ?
Where is the gateway in the microservice architecture ?
With Zuul Why did you come out again gateway?
Why do we choose Gatway?
1.neflix Not very reliable ,zuul2.0 Keep skipping tickets , Delayed release
2.SpringCloud Gateway Has the following characteristics
3.SpringCloud Gateway And Zuul The difference between
GateWay Model
Three core concepts
1.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 .
2.Predicate( Assertion )
The reference is java8 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 .
3.Filter( Filter )
refer to Spring In the frame GatewayFilter Example , Use filters , Requests can be modified before or after they are routed .
Gateway Workflow
The official website summarizes
Core logic :
Routing and forwarding + Execute the filter chain
Entry configuration
newly build Module
1. New module cloud-gateway-gateway9527
2. modify POM.xml
<dependencies>
<!-- gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- web Gateway Unwanted web rely on -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.zhang.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
3. establish application.yml file
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
# discovery:
# locator:
# enabled: true # Enable the registry routing function
# lower-case-service-id: true
routes:
- id: payment_routh
uri: http://localhost:8001
#uri: lb://cloud-payment-service # If there is a problem here , Please pay attention to dependency spring-cloud-starter-netflix-eureka-client Dependence cannot be wrong
predicates:
- Path=/payment/get/**
- id: payment_routh2
uri: http://localhost:8001
#uri: lb://cloud-payment-service
predicates:
- Path=/payment/lb/**
eureka:
instance:
hostname: cloud-gateway-service
client: # Service providers provider Sign up for eureka In the list of services
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eureka #,http://eureka7002.com:7002/eureka
#logging:
# level:
# root: debug
4. Main startup class
@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
public static void main(String[] args) {
SpringApplication.run(GateWayMain9527.class,args);
}
}
- 9527 How does the gateway do routing mapping ?
Gateway Gateway routing can be configured in two ways
1. In profile yml Middle configuration
2. Inject... Into the code RouteLocator Of Bean
establish config class
public class GateWayConfig {
/**
* Route builder
* @param routeLocatorBuilder
* @return
*/
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
routes.route("path_route_zhang"
, r->r.path("/guonei").uri("http://news.baidu.com/guonei"))
.build();
return routes.build();
}
}
Dynamic routing through microservice name
By default Gateway According to the service list of the registry , Create a dynamic route with the micro service name on the registry as the path to forward , So as to realize the function of dynamic routing .
It should be noted that uri The agreement is lb, Means to enable Gateway Load balancing function of .
modify application.yml
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true # Enable the registry routing function
# lower-case-service-id: true
routes:
- id: payment_routh
#uri: http://localhost:8001
uri: lb://cloud-payment-service # If there is a problem here , Please pay attention to dependency spring-cloud-starter-netflix-eureka-client Dependence cannot be wrong
predicates:
- Path=/payment/get/**
- id: payment_routh2
#uri: http://localhost:8001
uri: lb://cloud-payment-service
predicates:
- Path=/payment/lb/**
eureka:
instance:
hostname: cloud-gateway-service
client: # Service providers provider Sign up for eureka In the list of services
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eureka #,http://eureka7002.com:7002/eureka
lb://serviceName yes spring cloud gateway Load balancing created for us automatically in microservices uri.
Filter Use
1. What is it?
Routing filters can be used to modify incoming HTTP Requested and returned HTTP Respond to ; Routing filters can only specify routes to use .
Spring Cloud GateWay Built in many routing filters , They are all made up of GateWayFilter Factory class .
Custom filter
1. What can I do?
Global logging . Unified gateway authentication …
2. Custom global GlobalFilter
package com.zhang.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("************ The user is called null, For illegal users ,!!!!!!!!");
exchange.getResponse().setStatusCode(HttpStatus.NO_CONTENT);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
边栏推荐
- 60. Initial knowledge of wsgiref handwritten web framework +jinja2 module
- No module named 'yaml' solution
- Excellent résumé! Enfin quelqu'un a compris toutes les connexions SQL
- oop_引用类型变量传值
- 写代码遇到Qt相关问题
- Talk about distributed locks
- Redis cache avalanche, penetration, breakdown
- Visual studio production environment configuration scheme: slowcheetah
- Bean、
- Consul服务注册与发现
猜你喜欢
Super dry! Thoroughly understand golang memory management and garbage collection
Database review -- database recovery technology
Hand in hand practice a DAPP, the road to Web3.0!
A small program about daily habit clock in
5g at that time, where will driverless driving go in the future?
QT related problems encountered when writing code
Detailed explanation of type, user-defined type, preliminary understanding of structure
Consul服务注册与发现
Eureka self protection
Classic general pbootcms flower website template source code, adaptive mobile terminal, with background management
随机推荐
SPARK闲杂--为什么复用Exchange和subquery
Textview text up and down
图片浏览器
No module named 'yaml' solution
没那么大的组合数
5.2 database security
C # read and write txt files
5G正当时,无人驾驶未来将驶向何方?
#yyds干货盘点#Cross-origin 跨域请求
1. Flask Foundation
Redis data persistence
Deep learning 7 deep feedforward network 2
unity 自定义天空球模型防止被裁剪
行为型模式之策略模式
65、Restful规范
Detailed explanation of ansible automatic operation and maintenance (IV) preparation, use, command execution and example demonstration of playbook in ansible
How to convert STR in read list to float
Enjoy JVM -- knowledge about GC garbage collection
812. Maximum triangle area
演示集合注入