当前位置:网站首页>Microservice API gateway zuul
Microservice API gateway zuul
2022-07-03 15:34:00 【crysw】
1. Why
Why micro services need API gateway , Because in the microservice Architecture , Back end services are often not directly open to client , But through a API gateway On request url, route To the corresponding service . When adding API After gateway , A wall is created between third-party clients and back-end services , This wall directly communicates with the caller for permission control , Then distribute the request evenly to the background server .Spring Cloud Provides a solution : zuul gateway .
API gateway It provides a unified access to services in the microservice architecture , Client pass API Gateway access related services .API The definition of gateway is similar to Facade mode , It is equivalent to the facade of the whole microservice architecture , All client access is routed and filtered through it . It has achieved Request routing 、 Load balancing 、 Check filter 、 Service fault tolerance 、 Service aggregation and other functions .
2. Zuul
2.1 brief introduction
Zuul Routing is an integral part of microservice architecture , Provide dynamic routing , monitor , elastic , Edge services for security, etc .Zuul yes Netflix One of the products is based on JVM Load balancer on Routing and server side ( Microservice gateway ).
The main functions are agent , Dynamic routing , filter etc. .
Zuul Of GitHub Open source →
Official website information →Zuul You can talk to Eureka, Ribbon, Hystrix And other components . Use Eureka Gateway microservice architecture for service registration and discovery :

2.2 zuul What can I do?
route , Filter , Load balancing , Gray scale release, etc .
Grayscale Publishing , Also known as Canary release .
The origin is , The miners found that , Canaries are very sensitive to gas , The miner will go down the well before , Put a canary in the well first , Such as
The Canary stopped barking , It means high gas concentration .
After gray scale publishing begins , Start a new version of the app first , But it doesn't cut the flow directly , It's the testers who make progress in the new version
Online test , Start this new version of the app , It's our canary . If there is no problem , Then a small number of user flows
Import quantity to the new version , And then observe the running state of the new version , Collect all kinds of runtime data , If you make changes to the old and new versions at this time
Comparison of various data , It's called A/B test . There's nothing wrong with the new version , Then gradually expand the scope 、 Traffic , Move all users
Move to the new version .
routeThe function is responsible for forwarding external requests to specific service instances , It's the foundation of unified access portal .
3. Zuul Gateway microservice practice
Create gateway microservices [microservicecloud-zuul-gateway]
3.1 Import dependence
Import zuul and eureka client Dependence ( The gateway service itself needs to be registered to Eureka)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
3.2 The startup class starts the agent configuration
Startup class add @EnableZuulProxy annotation , Open the gateway proxy configuration .
/** * zuul Gateway startup class */
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy // Turn on Zuul Proxy configuration
public class ZuulGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulGatewayApplication.class, args);
}
}
3.3 Write the configuration
application.yml Add registration to the file eureka Configuration of .
server:
port: 10010
spring:
application:
name: zuul-gateway
## Eureka Client configuration
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://www.eureka01.com:7001/eureka,http://www.eureka02.com:7002/eureka,http://www.eureka03.com:7003/eureka
instance:
prefer-ip-address: true
instance-id: zuul-gateway-01
3.4 Configure routing rules
application.yml Configure routing rules in the file , There are several ways to configure routing rules . The following are listed respectively .
3.4.1 Mode one
## zuul Routing configuration
## Route mapping configuration 1, It is also the default configuration
zuul:
routes:
microservicecloud-provider:
path: /microservicecloud-provider
serviceId: microservicecloud-provider
microservicecloud-consumer:
path: /microservicecloud-consumer
serviceId: microservicecloud-consumer
Tips:
Forwarding pathpathAnd the name of the routed microservice instanceserviceIdConsistent time , It can be omitted completely zuul Dynamic routing configuration . That is, the above is the default configuration .
Only the mapping rules that appear in the configuration file will be created , And from Eureka Other services obtained in ,zuul Routing rules will not be created for them .
After starting the gateway microservice , We no longer visit directly The back-end service 了 , But through Gateway microservice Route and forward . Here are the test results of the default routing configuration .
3.4.2 Mode two
The default routing configuration rules are used in practical application scenarios , There are also problems . The instance name of the backend microservice is exposed in url in , There may be security risks . Let's customize path The way , The requested url Use in Alias , Again by Zuul gateway Route and forward to the back-end specific service provider .
## Route mapping configuration 2, Hide the microservice name , Use alias path
zuul:
routes:
myprovider:
path: /myprovider/**
serviceId: microservicecloud-provider
myconsumer:
path: /myconsumer/**
serviceId: microservicecloud-consumer
Or simplify it
## Route mapping configuration 2, Hide the microservice name , Use alias path
zuul:
routes:
myprovider.path: /myprovider/**
myprovider.serviceId: microservicecloud-provider
myconsumer.path: /myconsumer/**
myconsumer.serviceId: microservicecloud-consumer
The routing mapping configuration uses custom path after , The original default route mapping rules are also effective , You can still request in the above way . In order not to expose the back-end service instance name , We use custom path Of url request , Here are the test results .
3.4.3 Mode three
Use simpler zuul.routes.<serviceId>=<path> Configuration mode , The usage and test effect are the same as above .
zuul.routes.microservicecloud-provider=/myprovider/**
zuul.routes.microservicecloud-consumer=/consumer/**
## Route mapping configuration 3, Simplified edition
zuul:
routes:
microservicecloud-provider: /myprovider/**
microservicecloud-consumer: /consumer/**
3.5 Zuul Gateway configuration supplement
API gateway In the use of , You can also filter out micro service instances or... That do not want to use gateway routing rules through configuration items path. For example, sometimes ,
There are some services that we don't need to open to the outside world and are also accessed by the outside . We can use it at this time zuul.ignore-services Parameter to set a service name matching expression to define Rules that do not automatically create routes .zuul When automatically creating a service route, it will be judged according to the expression , If the service name matches the expression , that zuul The service will be skipped , Do not create routing rules for it .
such as , Set to zuul.ignored-services='*',zuul Routing rules will not be automatically created for all services .
zuul:
# Some routing configurations are omitted here ...
ignored-services: microservicecloud-api # Ignored microservice instances ; '*' Indicates that all micro service routes are ignored
ignored-patterns: /**/hello/** # Neglected path
The above configuration is microservicecloud-api Ignore ( Do not create routing rules ), The route of the service instance is filtered .
that http://localhost:port/microservicecloud-api/**/** Of url Requests will not be routed , The request failed .
You can also give the request gateway url Add Prefix Support .
zuul:
# Some routing configurations are omitted here ...
prefix: /gatewayto # Prefix of gateway access
To configure Prefix Test effect of access .
3.6 Zuul Gateway load balancing
because Zuul Automatic integration Ribbon and Hystrix, therefore Zuul Born with Load balancing and service fault tolerance .
3.7 View route information
Check the indispensable endpoint access dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Add endpoint exposure , Submit the configuration of endpoint access
# Turn on the endpoint of view route
management:
endpoints:
web:
exposure:
include: 'routes'
restart zuul Gateway microservice , visit http://localhost:10010/actuator/routes , You can view the routing information .
4. Zuul filter
4.1 Zuul Filter introduction
Dynamic routing function at real time , its Route mapping and Request forwarding Are made up of several different Zuul Filter finished . Route mapping from pre type Your filter is complete , It matches the request path with the configured routing rules , To find the destination address to forward ; Request forwarding from route type Filter to complete , Yes pre The routing address obtained by the type filter is forwarded .
therefore ,Zuul The filter can be said to be Zuul Realization API Gateway function is the most core component .
4.2 Zuul filter - Method statement
(1) filterType: This function needs to return a string to represent the type of filter , And this type is in HTTP The stages defined in the request process . stay Zuul in
By default, four filter types with different lifecycles are defined , As follows :
- pre: Execute before the request is routed to the target service , For example, authority verification 、 Print log and other functions ;
- route: Execute... When the request is routed to the target service .
- post: Execute... After the request is routed to the target service , For example, add header information to the response of the target service , Collect statistics and other functions ;
- error: Requests are executed when errors occur in other stages .
(2) filterOrder: adopt int Value to define the order in which filters are executed , The smaller the value, the higher the priority .
(3) shouldFilter: Return to one boolean Type to determine whether the filter is to be executed . We can use this method to specify the effective range of the filter .
(4) run: The specific logic of the filter . In this function , We can implement custom filtering logic , To determine whether to intercept the current request , Do not follow up > route , Or after the request route returns the result , Do some processing for the processing results, etc .
4.3 Zuul filter - Life cycle

Normal process :
Request arrives first pre filter Mapping request paths to routing rules , Then arrive routing filter Route and forward , The request reaches the real service provider , Perform the requested , Return results , Will arrive post filter after , Complete the response .
Abnormal flow :
- The whole process ,
pre perhaps routing filterSomething unusual happened , They'll go straight inerror filter, stayerror filterAfter processing , Will give the request topost filter, Last return to user . - If it is
error filterSomething unusual happened to me , Eventually, it will enterpost filter, And then back to the user . - If it is
post filterSomething unusual happened , Will jump toerror filter, But with thepre and routing filterThe difference is , The request will not arrive againpost filter, Instead, it is returned directly to the user .
4.4 To write Zuul filter
Zuul The filter of gateway can also do Permission to check exception handling And so on .
Step blog : Explain profound theories in simple language SpringCloud→ chapter 6.5.4 To write Zuul filter
5. Personal blog
Welcome to personal blog : https://www.crystalblog.xyz/
Alternate address : https://wang-qz.gitee.io/crystal-blog/
边栏推荐
- CString的GetBuffer和ReleaseBuffer使用说明
- The markdown file obtains the pictures of the network and stores them locally and modifies the URL
- Kubernetes 进阶训练营 Pod基础
- Jvm-04-runtime data area heap, method area
- Popular understanding of gradient descent
- Popular understanding of linear regression (I)
- QT common sentence notes
- leetcode_ Power of Four
- Driver and application communication
- Kubernetes带你从头到尾捋一遍
猜你喜欢

QT use qzxing to generate QR code

Reading notes of "micro service design" (Part 2)

String functions that you need to know

详解指针进阶2

Visual upper system design and development (Halcon WinForm) -3 Image control

Seckill system 3- product list and product details

Tensorflow realizes verification code recognition (I)

Popular understanding of linear regression (II)
![[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller](/img/a4/2156b61fbf50db65fdf59c8f5538f8.png)
[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller

Introduction, use and principle of synchronized
随机推荐
从 flask 服务端代码自动生成客户端代码 -- flask-native-stubs 库介绍
视觉上位系统设计开发(halcon-winform)-6.节点与宫格
XWiki安装使用技巧
Halcon and WinForm study section 2
视觉上位系统设计开发(halcon-winform)-1.流程节点设计
Creation and destruction of function stack frames
Subclass hides the function with the same name of the parent class
Visual upper system design and development (Halcon WinForm) -6 Nodes and grids
Popular understanding of linear regression (I)
Visual upper system design and development (Halcon WinForm) -1 Process node design
在MapReduce中利用MultipleOutputs输出多个文件
Qt常用语句备忘
Redis cache penetration, cache breakdown, cache avalanche solution
大csv拆分和合并
socket. IO build distributed web push server
Find mapping relationship
Seckill system 3- product list and product details
leetcode_ Power of Four
Atlas atlas torque gun USB communication tutorial based on mtcom
Kubernetes vous emmène du début à la fin
