当前位置:网站首页>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 .
边栏推荐
- Win10 uses docker to pull the redis image and reports an error read only file system: unknown
- Hengyuan cloud_ Can aiphacode replace programmers?
- Solution of Xiaomi TV's inability to access computer shared files
- Minecraft air Island service
- 【Go实战基础】gin 如何获取 GET 和 POST 的请求参数
- Taking the upgrade of ByteDance internal data catalog architecture as an example, talk about the performance optimization of business system
- Analysis and solution of a classical Joseph problem
- Minecraft install resource pack
- [staff] time sign and note duration (full note | half note | quarter note | eighth note | sixteenth note | thirty second note)
- Don't spend money, spend an hour to build your own blog website
猜你喜欢
Finishing the interview essentials of secsha system!!!
QT -- how to set shadow effect in QWidget
【Go实战基础】gin 如何设置路由
Minecraft module service opening
Matplotlib剑客行——布局指南与多图实现(更新)
Redis zadd导致的一次线上问题排查和处理
MYSQL安装出现问题(The service already exists)
Talk about the secret of high performance of message queue -- zero copy technology
Taking the upgrade of ByteDance internal data catalog architecture as an example, talk about the performance optimization of business system
Win10 uses docker to pull the redis image and reports an error read only file system: unknown
随机推荐
Gocv image cutting and display
我服了,MySQL表500W行,居然有人不做分区?
1、 QT's core class QObject
[go practical basis] gin efficient artifact, how to bind parameters to structures
微服务实战|熔断器Hystrix初体验
Use of libusb
图像变换,转置
【Go实战基础】gin 如何获取 GET 和 POST 的请求参数
"Redis source code series" learning and thinking about source code reading
Ora-12514 problem solving method
Installing Oracle database 19C for Linux
Flink-使用流批一体API统计单词数量
Npoi export word font size correspondence
[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)
Select sort and insert sort
概念到方法,绝了《统计学习方法》——第三章、k近邻法
查看was发布的应用程序的端口
Multi version concurrency control mvcc of MySQL
长篇总结(代码有注释)数构(C语言)——第四章、串(上)
小米电视不能访问电脑共享文件的解决方案