(picture from network)
With the increasing scale of microservices, the following problems will appear in the microservice system
- From the perspective of operation and maintenance, the client sends a service request, which is forwarded to different service instances through the routing of F5,Nginx and other devices through load balancing distribution. Therefore, the operation and maintenance personnel need to maintain these service lists. When the instance increases or decreases or the IP address changes, the probability of manually modifying the maintenance configuration will increase with the scale of the system
- From the perspective of development and testing, permission verification mechanisms, such as login status verification or signature verification, are generally added to the interface of microservices. With the expansion of the scale of microservices, the redundancy of these verification logic becomes more and more, the difficulty of development and maintenance becomes more and more, and the testing burden of testers will become more and more
1. Introduction to spring cloud zuul
In order to solve these common architecture problems, the concept of API gateway came into being. It is similar to the Facade pattern of object-oriented design. It is like the Facade of microservice architecture system. All external client accesses need to be scheduled and filtered through it. Spring Cloud provides an API gateway component Spring Cloud Zuul based on Netflix Zuul implementation
Zuul is a member of Netflix OSS. It is a load balancer based on JVM routing and server. It provides a service framework in terms of routing, monitoring, elasticity and security. Zuul can be used with Eureka, Ribbon, Hystrix and other components.
The core of Zuul is filters. Through these filters, we can expand many functions, such as:
- Dynamic routing: dynamically route client requests to different back-end services, and do some logical processing, such as aggregating data returns from multiple services
- Request monitoring: it can monitor the requests of the whole system, record detailed request response logs, and count the current system access and monitoring status in real time.
- Authentication: Authenticate every access request, reject illegal requests, and protect the back-end services.
- Pressure test: Stress testing is a very important work. For example, some e-commerce companies need to simulate more real user concurrency to ensure the stability of the system during major activities. Zuul can dynamically forward requests to the cluster of back-end services, and can also identify test traffic and real traffic for special processing.
- Gray level release: gray level release can ensure the stability of the overall system. Problems can be found and adjusted at the initial gray level to ensure its impact.
2. Getting started with spring cloud zuul
Reference code: GitHub - PNZBEIJINGL/spring-cloud-lab
service | IP | port | |
eureka-peer | 127.0.0.1 | 1000 | Eureka service registry |
ms-customer | 127.0.0.1 | 8001 | customer service |
api-gateway | 127.0.0.1 | 8005 | Gateway service |
Learn how to use Spring Cloud Zuul to implement API gateway service through the following simple example
two point one IP oriented routing
1. Create a Spring boot project and introduce the spring cloud starter zuul dependency into pom.xml
<dependencies> <!--introduce zuul--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Registration service provider --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> </dependencies>
2. Start the main class, add @ EnableZuulProxy annotation and start zuul function
@EnableZuulProxy @SpringCloudApplication public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } }
3. Add zuul routing settings in the application.properties file. The routing rules and references are as follows
1)zuul.routes.<route>.path The < route > part of the configuration routing rule is the name of the route, and any string can be defined
- ? Match single character
- * Matches any number of characters, excluding multi-level paths
- ** Matches any number of characters, including multi-level paths
2) Zuul. Routes. < route >. url configuration url is used to configure the service address to which the path compliant request path is routed. The < route > part is the name of the route, and any string can be defined
server.port=8005 spring.application.name=API-GATEWAY zuul.routes.api-a-url.path=/api-a-url/** zuul.routes.api-a-url.url=http://localhost:8001/
test
Start MS customer service and API gateway service
visit: http://127.0.0.1:8005/api-a-url/time
Visible when accessing http://127.0.0.1:8005/api-a-url/time, the API gateway service will route the request to http://localhost:8001/time On the microservice interface provided
2.2 service oriented routing
Spring Cloud Zuul realizes seamless integration with Spring Cloud Eureka, and can realize routing path instead of url
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency>
Modify applicaiton.properties
zuul.routes.api-b-url.path=/api-b-url/** #MS-CUSTOMER is the microservice name of the route zuul.routes.api-b-url.url=MS-CUSTOMER ############ Eureka ################ #Service registry IP eureka.instance.hostname=127.0.0.1 eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:1000/eureka/ ############ Eureka ################
test
Start Eureka peer service, Ms customer service and API gateway service
visit: http://127.0.0.1:8005/api-b-url/time
In this way, the configuration mode of service-oriented routing is realized
2.3 request filtering
Since the gateway service is added, external clients have a unified access to our system, so they can complete the checksum filtering when the request arrives, so as to avoid the request delay caused by filtering with code after forwarding. Implementing checksum filtering in the gateway can also reduce redundant code
Zuul allows developers to intercept and filter requests by defining filters on the API gateway. The implementation method is relatively simple. They only need to inherit the ZuulFilter abstract class and implement the abstract methods. For example, to create a filter, AccessFilter inherits ZuulFilter. To create a filter, you need to implement four abstract methods. See the code below for the method description
public class AccessFilter extends ZuulFilter { private static Logger log = LoggerFactory.getLogger(AccessFilter.class); /** * pre - The pre filter is executed before the request is routed. It is usually used to process identity authentication, logging, etc; * route - After the route is executed, it is called before the service call; * error - Any filter is executed when an exception occurs or when the remote service call has no feedback (timeout), which is usually used to handle exceptions; * post - It is called after the route or error is executed. It is generally used to collect service information, count service performance indicators, etc. it can also do special processing on the response results * * @return */ @Override public String filterType() { return "pre"; } /** * Filters of the same type are executed in natural order * The smaller the return value, the higher the execution order * @return */ @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); Object accessTocken = request.getParameter("accessTocken"); if (accessTocken == null) { requestContext.setSendZuulResponse(false); requestContext.setResponseStatusCode(401); return null; } return null; } }
After creating a filter, you need to create it as a specific Bean to start the filter. Refer to
@EnableZuulProxy @SpringCloudApplication public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } @Bean public AccessFilter accessfilter(){ return new AccessFilter(); } }
test
Start Eureka peer service, Ms customer service and API gateway service
visit: http://127.0.0.1:8005/api-b-url/time 401 error will be returned
visit: http://127.0.0.1:8005/api -The service can be accessed correctly when b-url / time? Accesstoken = 123