Why do we need a microservice gateway
Different microservices generally have different network addresses, while external clients may need to call multiple service interfaces.
Can fulfill a business requirement. For example, a movie ticket collection APP, may call back the movie classification micro service, users
Microservices, payment microservices, etc. If the client communicates directly with the micro-service, there will be some problems:
# The client will request different micro services many times to increase the complexity of the client.
# There are cross-domain requests, which are relatively complex to handle in certain scenarios
# Authentication is complex, and each service needs independent authentication
# Difficult to reconstruct, as the project iterates, it may be necessary to re-divide the micro services if the client communicates directly with the micro services.
Trust, then restructuring will be difficult to implement
# Some microservices may use other protocols, and direct access may be difficult.
All these problems can be solved by means of micro-service gateway. Microsoft Gateway is between client and server.
In the interlayer, all external requests go through the micro-service gateway first.
What is Zuul
Zuul is Netflix's open-source micro-service gateway, which can work with Eureka,Ribbon,Hystrix and other components.
Use. The core of the Zuul component is a series of filters that perform the following functions:
# Identity authentication and security: Identify authentication requirements for each resource and reject those that do not conform
# Review and monitoring:
## Dynamic Routing: Dynamic Routing of Requests to Different Backend Clusters
# Stress testing: Increase traffic to the cluster gradually to understand performance
# Load allocation: Allocate the corresponding capacity for each load type and discard requests that exceed the limit
# Static Response Processing: Response at Edge Position to Avoid Forwarding to Internal Cluster
# Multi-area resilience: Cross-domain AWS Region for request routing, designed to achieve ELB (Elastic Load Balancing) enabled
Diversification
Spring Cloud integrates and enhances Zuul.
With Zuul, architecture diagrams evolve into the following forms
1.1 Management Background Microservice Gateway
1. Dependence
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> </dependencies>
2. Startup class
@SpringBootApplication @EnableEurekaClient @EnableZuulProxy public class ManagerApplication { public static void main(String[] args) { SpringApplication.run(ManagerApplication.class); } }
3. Configuration files
4. Filters
@Component public class ManagerFilter extends ZuulFilter { @Autowired private JwtUtil jwtUtil; /** * Execute before or after the request * @return */ @Override public String filterType() { return "pre"; } /** * The order of execution of multiple filters, the smaller the number, the earlier the execution. * @return */ @Override public int filterOrder() { return 0; } /** * Whether the current filter opens true means open * @return */ @Override public boolean shouldFilter() { return true; } /** * The operation performed in the filter return s any ojbect value to indicate continued execution * setsendzullRespponse(false)Represents no further execution * @return * @throws ZuulException */ @Override public Object run() throws ZuulException { System.out.println("After the background filter!"); RequestContext requestContext = RequestContext.getCurrentContext(); //request domain HttpServletRequest request = requestContext.getRequest(); if(request.getMethod().equals("OPTIONS")){ return null; } if(request.getRequestURI().indexOf("login")>0){ return null; } //Get header information String header = request.getHeader("Authorization"); if(header!=null && !"".equals(header)){ if(header.startsWith("Bearer ")){ String token = header.substring(7); try { Claims claims = jwtUtil.parseJWT(token); String roles = (String) claims.get("roles"); if(roles.equals("admin")){ //Forward the header message and let it go requestContext.addZuulRequestHeader("Authorization", header); return null; } }catch (Exception e){ e.printStackTrace(); requestContext.setSendZuulResponse(false);//Termination of operation } } } requestContext.setSendZuulResponse(false);//Termination of operation requestContext.setResponseStatusCode(403); requestContext.setResponseBody("Insufficient authority"); requestContext.getResponse().setContentType("text/html;charset=utf-8"); return null; } }
filterType: Returns a string representing the type of filter and defines four different lifecycle transitions in zuul
The types of filters are as follows:
pre: Called before the request is routed
route: Called at the time of a routing request
post: Called after the route and error filters
Error: Called when an error occurs while processing a request
filterOrder: Defines the order of execution of filters by an int value
shouldFilter: Returns a boolean type to determine whether the filter is to be executed, so this function can be used
Realize the switch of the filter. In the previous example, we returned true directly, so the filter always works.
run: The specific logic of the filter.
2.1 Management Background Microservice Gateway
1. Dependence
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> </dependencies>
2. Startup class
@SpringBootApplication @EnableEurekaClient @EnableZuulProxy public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class); } }
3. Configuration files
4. Filters
@Component public class WebFilter extends ZuulFilter { @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { //Get the request context RequestContext currentContext = RequestContext.getCurrentContext(); //Get the request field HttpServletRequest request = currentContext.getRequest(); //Get header information String header = request.getHeader("Authorization"); //Judge whether there is header information if(header!=null && !"".equals(header)){ //Continue downloading header information currentContext.addZuulRequestHeader("Authorization", header); } return null; } }