当前位置:网站首页>Micro service practice | introduction and practice of zuul, a micro service gateway
Micro service practice | introduction and practice of zuul, a micro service gateway
2022-07-02 09:11:00 【_ Time boiled the rain】
The function of gateway
In microservice Architecture , The address of the service instance may often change , So we can't directly expose the address of the service . If every microservice directly exposes interfaces , It can lead to a series of problems , For example, the call is too complex , Involving accounts 、 Permissions cannot be handled uniformly . In addition, based on the design criteria of high cohesion and low coupling , We should also cut the internal system and external system .
therefore , At this time, an independent component is needed to handle external requests , This component is the service gateway . Service gateway is to simplify the calling logic of the front end , Usually, the related authentication logic will also be implemented , Respond to different data according to different external requests , So as to simplify the complexity of calls between internal and external systems .
The service gateway is responsible for service request routing 、 Combination and protocol conversion . All requests from the client go through the service gateway first , It then routes the request to the appropriate microservice . Service gateways often process a request by invoking multiple microservices and merging the results , It can be a friendly conversion between the external and internal responses of the system .
This article will first focus on Zuul Components .
Spring Cloud Gateway components Zuul Introduce
Zuul yes Netflix Open source products of the company , It is called the first generation gateway , It's also Spring Cloud The previous versions use a microservice gateway component that provides dynamic routing by default .Zuul Receive all external requests , And forward the request to the corresponding back-end service . As a front-end service ,Zuul Designed to achieve dynamic routing , monitor , Flexibility, security and other functions .
Zuul Different types of filter Used to process requests , these filter Let's implement the following functions :
- Authority control and security : Can identify the information needed for authentication and reject requests that do not meet the conditions .
- monitor : Significant data and statistical results with edge location tracking , This leads to an accurate production view .
- Dynamic routing : Dynamically route requests to different clusters in the background as needed .
- Pressure test : Gradually increase the traffic to the cluster , To understand performance .
- Load balancing : Each load type is assigned a corresponding capacity , And discard requests that exceed the qualified value
- Static resource processing : Directly in zuul Handle the response of static resources , To avoid forwarding it to the internal cluster .
Zuul Gateway combat
In the previous Introduction , We launched the registry registry,dms service , and app service , When asked , Call directly app Service Interface ,app The service called again dms service :

After adding the gateway service , It's like this :
Next , We created zuul service :
1、 Create services
Create submodule zuul,pom.xml introduce eureka-client and zuul Dependence
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- zuul route -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
2、 create profile
server:
port: 8004
spring:
application:
name: zuul
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/
feign:
hystrix:
enabled: true
zuul:
routes:
app: # Activities
path: /app/** # Configuration request URL Request rules for
serviceId: app # Appoint Eureka Services in the registry id
dms: # Activities
path: /dms/** # Configuration request URL Request rules for
serviceId: dms # Appoint Eureka Services in the registry id
logging:
pattern:
console: '%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} - %msg%n'
3、 establish Zuul filter
/** * @Author: official account : The programmer 965 * @create 2022-06-30 **/
@Component
public class MyZuulFilter extends ZuulFilter {
// pre : Can be called before the request is routed.
// route : Called when routing a request
// post : stay route and error The filter is then called
// error : Called when an error occurs while processing a request
@Override
public String filterType() {
return "pre";// Front filter
}
// adopt int Value to define the order in which filters are executed , The priority for 0, The greater the number , The lower the priority
@Override
public int filterOrder() {
return 0;
}
// Return to one boolean Type to determine whether the filter is to be executed , So the filter switch can be realized through this function
@Override
public boolean shouldFilter() {
return true;// Here is true, Explain the need to filter
}
// The specific logic of the filter .
@Override
public Object run() throws ZuulException {
// Get context
RequestContext currentContext = RequestContext.getCurrentContext();
HttpServletRequest request = currentContext.getRequest();
String accessToken = request.getParameter("accessToken");
if (StringUtils.isEmpty(accessToken)) {
//setSendZuulResponse(false) Make zuul Filter the request , Do not route
currentContext.setSendZuulResponse(false);
// Set the error code returned
currentContext.setResponseStatusCode(401);
currentContext.setResponseBody("AccessToken is null");
return null;
}
System.out.println(" Get AccessToken by :"+accessToken);
// Otherwise, normal execution of business logic .....
return null;
}
}
4、 Write the startup class
Pay attention to adding @EnableZuulProxy annotation
/** * @Author: official account : The programmer 965 * @create 2022-06-30 **/
@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
5、 Start validation
This is the time , We will directly request app Interface address of , Change to gateway zuul The address and port of :http://localhost:8004/app/index

You can see , There is no token Access authorization authentication failed !
summary
Summarize the role of gateway :
- Simplify the complexity of client calls , Unified processing of external requests .
- Data clipping and aggregation , According to different interface requirements , Provide external interface after data processing
- Multi platform support , Provide different gateway support for different clients .
- Micro service transformation of legacy system , It can be used as a transfer component of new and old systems .
- Unified handling of security during invocation 、 Permission problems .
边栏推荐
- C language implementation of mine sweeping game
- C# 高德地图 根据经纬度获取地址
- 【Go实战基础】如何安装和使用 gin
- Linux binary installation Oracle database 19C
- 分布式服务架构精讲pdf文档:原理+设计+实战,(收藏再看)
- Avoid breaking changes caused by modifying constructor input parameters
- NPOI 导出Word 字号对应
- 【Go实战基础】gin 如何获取 GET 和 POST 的请求参数
- Multi version concurrency control mvcc of MySQL
- Analysis and solution of a classical Joseph problem
猜你喜欢

Openshift container platform community okd 4.10.0 deployment

Multi version concurrency control mvcc of MySQL

Solution of Xiaomi TV's inability to access computer shared files

概念到方法,绝了《统计学习方法》——第三章、k近邻法

commands out of sync. did you run multiple statements at once

ORA-12514问题解决方法

C4D quick start tutorial - C4d mapping

以字节跳动内部 Data Catalog 架构升级为例聊业务系统的性能优化
![[staff] time sign and note duration (full note | half note | quarter note | eighth note | sixteenth note | thirty second note)](/img/bf/2b0b9c640bdad2c55293f905a22055.jpg)
[staff] time sign and note duration (full note | half note | quarter note | eighth note | sixteenth note | thirty second note)

Minecraft air Island service
随机推荐
NPOI 导出Word 字号对应
Dix ans d'expérience dans le développement de programmeurs vous disent quelles compétences de base vous manquez encore?
MYSQL安装出现问题(The service already exists)
Multi version concurrency control mvcc of MySQL
oracle修改数据库字符集
Taking the upgrade of ByteDance internal data catalog architecture as an example, talk about the performance optimization of business system
Matplotlib swordsman Tour - an artist tutorial to accommodate all rivers
Oracle delete tablespace and user
微服务实战|负载均衡组件及源码分析
Oracle修改表空间名称以及数据文件
Hengyuan cloud_ Can aiphacode replace programmers?
一个经典约瑟夫问题的分析与解答
机器学习实战:《美人鱼》属于爱情片还是动作片?KNN揭晓答案
Openshift container platform community okd 4.10.0 deployment
History of Web Technology
C# 百度地图,高德地图,Google地图(GPS) 经纬度转换
Qt的右键菜单
数构(C语言--代码有注释)——第二章、线性表(更新版)
[staff] time mark and note duration (staff time mark | full note rest | half note rest | quarter note rest | eighth note rest | sixteenth note rest | thirty second note rest)
Webflux responsive programming