当前位置:网站首页>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 .
route
The 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 pathpath
And the name of the routed microservice instanceserviceId
Consistent 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 ur
l 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 filter
Something unusual happened , They'll go straight inerror filter
, stayerror filter
After processing , Will give the request topost filter
, Last return to user . - If it is
error filter
Something unusual happened to me , Eventually, it will enterpost filter
, And then back to the user . - If it is
post filter
Something unusual happened , Will jump toerror filter
, But with thepre and routing filter
The 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/
边栏推荐
- Matlab r2011b neural network toolbox precautions
- Seckill system 3- product list and product details
- redis缓存穿透,缓存击穿,缓存雪崩解决方案
- 整形和浮点型是如何在内存中的存储
- Introduction to redis master-slave, sentinel and cluster mode
- Jvm-02-class loading subsystem
- 视觉上位系统设计开发(halcon-winform)-5.相机
- Location of software installation information and system services in the registry
- Popular understanding of decision tree ID3
- Using Tengine to solve the session problem of load balancing
猜你喜欢
北京共有产权房出租新规实施的租赁案例
Jvm-03-runtime data area PC, stack, local method stack
CString getbuffer and releasebuffer instructions
[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller
Second kill system 3 - list of items and item details
Halcon与Winform学习第二节
Idea does not specify an output path for the module
redis缓存穿透,缓存击穿,缓存雪崩解决方案
高并发下之redis锁优化实战
C语言刷题~Leetcode与牛客网简单题
随机推荐
驱动与应用程序通信
Visual host system design and development (Halcon WinForm)
Find mapping relationship
C语言刷题~Leetcode与牛客网简单题
Visual upper system design and development (Halcon WinForm) -2 Global variable design
Introduction to redis master-slave, sentinel and cluster mode
Digital image processing -- popular Canny edge detection
win32创建窗口及按钮(轻量级)
北京共有产权房出租新规实施的租赁案例
《微服务设计》读书笔记(上)
The difference between RAR and zip files
Unity function - unity offline document download and use
Popular understanding of linear regression (II)
[daily training] 395 Longest substring with at least k repeated characters
找映射关系
Halcon与Winform学习第一节
Characteristics of MySQL InnoDB storage engine -- Analysis of row lock
C language brush questions ~leetcode and simple questions of niuke.com
Popular understanding of linear regression (I)
视觉上位系统设计开发(halcon-winform)-1.流程节点设计