当前位置:网站首页>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 .
边栏推荐
- Ora-12514 problem solving method
- 2022/2/14 summary
- 数构(C语言)——第四章、矩阵的压缩存储(下)
- Minecraft plug-in service opening
- "Redis source code series" learning and thinking about source code reading
- QT drag event
- 微服务实战|Eureka注册中心及集群搭建
- Leetcode sword finger offer brush questions - day 22
- Judge whether it is Sudoku
- Taking the upgrade of ByteDance internal data catalog architecture as an example, talk about the performance optimization of business system
猜你喜欢
C language implementation of mine sweeping game
数构(C语言)——第四章、矩阵的压缩存储(下)
概率还不会的快看过来《统计学习方法》——第四章、朴素贝叶斯法
I've taken it. MySQL table 500W rows, but someone doesn't partition it?
我服了,MySQL表500W行,居然有人不做分区?
数构(C语言--代码有注释)——第二章、线性表(更新版)
十年開發經驗的程序員告訴你,你還缺少哪些核心競爭力?
Redis安装部署(Windows/Linux)
知识点很细(代码有注释)数构(C语言)——第三章、栈和队列
汉诺塔问题的求解与分析
随机推荐
C# 高德地图 根据经纬度获取地址
QT -- how to set shadow effect in QWidget
Troubleshooting and handling of an online problem caused by redis zadd
Installing Oracle database 19C RAC on Linux
随笔:RGB图像颜色分离(附代码)
「Redis源码系列」关于源码阅读的学习与思考
微服务实战|熔断器Hystrix初体验
京东高级工程师开发十年,编写出:“亿级流量网站架构核心技术”
[go practical basis] gin efficient artifact, how to bind parameters to structures
Programmers with ten years of development experience tell you, what core competitiveness do you lack?
Introduction to the basic concept of queue and typical application examples
CSDN Q & A_ Evaluation
cmd窗口中中文呈现乱码解决方法
使用IBM MQ远程连接时报错AMQ 4043解决思路
微服务实战|负载均衡组件及源码分析
Solution and analysis of Hanoi Tower problem
Count the number of various characters in the string
Matplotlib剑客行——没有工具用代码也能画图的造型师
Redis sorted set data type API and application scenario analysis
Hengyuan cloud_ Can aiphacode replace programmers?