In the microservice architecture, several basic service management components are required, including service registration and discovery, service consumption, load balancing, circuit breakers, intelligent routing, configuration management, etc. These basic components cooperate with each other to form a Simple microservice system. A simple microservice system is shown below:
Note: Service A and Service B can be called mutually, and they are forgotten when drawing. And the configuration service is also registered to the service registry.
In the Spring Cloud microservice system, a common load balancing method is that the client's request first passes through load balancing (zuul, Ngnix), then reaches the service gateway (zuul cluster), and then to the specific service. , The service is registered to the highly available service registry cluster, all configuration files of the service are managed by the configuration service (described in the next article), and the configuration file of the configuration service is placed in the git warehouse, which is convenient for developers to change the configuration at any time.
1. Introduction to Zuul
The main function of Zuul is routing and filtering. The routing function is part of the microservices, such as api/user forwarded to the user service, and /api/shop forwarded to the shop service. By default, zuul combines with Ribbon to realize the function of load balancing.
Zuul has the following functions:
- Authentication
- Insights
- Stress Testing
- Canary Testing
- Dynamic Routing
- Service Migration
- Load Shedding
- Security
- Static Response handling
- Active/Active traffic management
2. Preparation
Continue to use the project in the previous section. On the original project, create a new project.
Three, create service-zuul project
The pom.xml file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.forezp</groupId>
<artifactId>service-zuul</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>service-zuul</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>com.forezp</groupId>
<artifactId>sc-f-chapter5</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
</dependencies>
</project>
Add the annotation @EnableZuulProxy to its entry applicaton class to enable the zuul function:
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceZuulApplication {
public static void main(String[] args) {
SpringApplication.run( ServiceZuulApplication.class, args );
}
}
Add the configuration file application.yml and the following configuration code:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8769
spring:
application:
name: service-zuul
zuul:
routes:
api-a:
path: /api-a/**
serviceId: service-ribbon
api-b:
path: /api-b/**
serviceId: service-feign
First, specify the address of the service registration center as http://localhost:8761/eureka/, the service port as 8769, and the service name as service-zuul; all requests beginning with /api-a/ are forwarded to the service-ribbon service; All requests starting with /api-b/ are forwarded to the service-feign service;
Run these five projects in turn; open the browser to visit: http://localhost:8769/api-a/hi?name=forezp; the browser displays:
hi forezp,i am from port:8762
Open the browser to visit: http://localhost:8769/api-b/hi?name=forezp; the browser displays:
hi forezp,i am from port:8762
This shows that zuul plays the role of routing
Four, service filtering
Zuul is not only routing, but also filtering and doing some security verification. Continue the renovation project;
@Component
public class MyFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(MyFilter.class);
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
Object accessToken = request.getParameter("token");
if(accessToken == null) {
log.warn("token is empty");
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
try {
ctx.getResponse().getWriter().write("token is empty");
}catch (Exception e){}
return null;
}
log.info("ok");
return null;
}
}
- filterType: Returns a string representing the type of filter. Four filter types with different life cycles are defined in zuul, as follows:
- pre: before routing
- routing: when routing
- post: After routing
- error: send an error call
- filterOrder: the order of filtering
- shouldFilter: Here you can write a logical judgment, whether to filter, this article is true, always filter.
- run: The specific logic of the filter. Available is very complicated, including checking sql, nosql to determine whether the request has permission to access.
Visit at this time: http://localhost:8769/api-a/hi?name=forezp; the webpage shows:
token is empty
Visit http://localhost:8769/api-a/hi?name=forezp&token=22; the
webpage shows:
hi forezp,i am from port:8762
Download the source code of this article:
https://github.com/forezp/SpringCloudLearning/tree/master/sc-f-chapter5
Read more
Summary of the simplest SpringCloud tutorials in history
Summary of Java Interview Questions Series
5. Reference materials:
http://blog.csdn.net/forezp/article/details/69939114
http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html