My blog: programmer xiaoxiao sheng, welcome to browse blog! , search for blogs to add wechat official accounts.

In the previous SpringCloud basics tutorial (9)-Hystrix Service Monitoring (2), we took an in-depth look at Hystrix service monitoring. This chapter will explore another component of microservices, gateway.

    Copy the code

preface

What is Zuul,Zuul can be said to be a gate, all requests from the front end, through Zuul, can achieve dynamic routing and forwarding, monitoring, security and other edge service applications. For example, it can be used as an access point for unified resources, load balancing, etc. Why do you need such a component? Netflix developed such a product with the following in mind: API diversity and high traffic can cause too many problems to be warned. So we need such system components to deal with these situations.

I. Functions provided by Zuul

  • Authentication and security – Identifies every request to access a resource and rejects unmet requests
  • Insight and monitoring, tracking meaningful data and statistics in order to generate meaningful production views
  • Dynamic routing, dynamically routing requests to different back-end clusters as needed, (most important function)
  • Stress testing, incrementally increasing cluster traffic, evaluating performance
  • Limit traffic, allocate capacity for each request, and discard requests that exceed the limit
  • Handle static responses, building responses directly at the edges rather than forwarding them to the internal cluster

Zuul Quick Start

A new Maven project introduces Zuul’s dependency and Eureka’s dependency. We forward requests to obtain service information from Eureka. Zuul’s dependencies are integrated with Hystrix and ribbon by default

<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>Copy the code

Create a GateWayApplication startup class and add @EnableZuulProxy, @SpringBootApplication, @EnableDiscoveryClient, and @Enablecircuitbreaker: Represents a SpringBoot program that enables service discovery and service fusing,

import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringCloudApplication @EnableZuulProxy public class GateWayApplication { public static void main(String[] args) { SpringApplication.run(GateWayApplication.class); }}Copy the code

Of course we can use @SpringCloudApplication as an annotation, It can be seen from the source code that @SpringCloudApplication contains @SpringBootApplication, @EnableDiscoveryClient and @Enablecircuitbreaker:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public @interface SpringCloudApplication {
}
Copy the code

Configure applicaton. yml, configure the port number, configure the URL to connect to Eureka, configure zuul:

Server: port: 9876 Eureka: instance: instance-id: gateway1 hostname: eureka7001.com defaultZone: http://eureka7001.com:7001/eureka/ zuul: ignored-services: "*" routes: server-provider: path: /server-provider/*Copy the code

There are the following configurations under Routes

The first:

zuul: ignored-services: "*" routes: server-provider: /server-provider/ : /server-provider/ : /server-provider/ : /server-provider/ : /server-provider/ : /server-provider/ : /server-provider/ /server-provider/*Copy the code

The second:

Zuul: ignored-services: "*" routes: server-a: # route: / provider/ /server-provider/* # Config service register Eureka service name, refers to the spring. Application. Name configuration serviceId: server-providerCopy the code

The third:

Zuul: ignored-services: "*" routes: server-b: # # /server-provider/* # config server register the service name in Eureka, which refers to the configuration URL of spring. Application. Name in Eureka: http://localhost:5168/ # Not through EurekaCopy the code

Next, we start Eureka center, two service providers: server-provider, start Zuul gateway service, check Eureka monitoring page:

Then we accessed through the following URL: http://localhost:9876/server-provider/sayHello? Name =1, we can see that we have implemented routing through the Zuul gateway, the service provider can also return the result of the request, and achieve load balancing:

Three, Zuul filter

3.1 Introduction to Filters

In addition to routing forwarding, Zuul can realize different functions based on different requirements in actual enterprise applications. Zuul can implement interface permission verification, traffic limiting, statistics, and so on through filters. Zuul defines four different filter types:

We can interpret this as calling at different times of the request:

  • Pre: This filter is invoked before the request is forwarded and is used for authentication, etc
  • Routing: This route is used to route to different back-end services. The underlying layer can request microservices using HttpClient or the Ribbon
  • Post: When the request is forwarded to the microservice, the filter of the current type is invoked. Usually used for HTTP headers in response to god and standard jobs, collecting statistics, and so on
  • Error: The filter is executed when an error occurs

3.2 User-defined Filters Implement Token Authentication

Custom filters need to integrate com.net flix. Zuul. ZuulFilter class, and implement the abstract methods needed to achieve purpose, here we simple implementation through Token validation:

import com.alibaba.fastjson.JSONObject; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * extends ZuulFilter {private Logger logger=LoggerFactory.getLogger(TokenFilter.class); /** * return filterType "pre"/"route"/"post"/" error "** @return */ @override public String filterType() {return pre; ** @override public int filterOrder() {return 0; } @override public Boolean shouldFilter() {return true; } /** * When shouldFilter() returns true * execute the specific logic in run. The return value has no meaning in the current version ** @return * @throws ZuulException */ @override public Object run() throws ZuulException { RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); HttpServletResponse response = context.getResponse(); Token = request. GetHeader ("token"); JSONObject jsonObject=new JSONObject(); / / if the token is empty, return status for 401, return json information if (StringUtils. IsEmpty (token)) {context. SetSendZuulResponse (false); context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); jsonObject.put("code",401); jsonObject.put("msg","UNAUTHORIZED"); context.setResponseBody(jsonObject.toJSONString()); logger.info("msg:{}",jsonObject); } else {// otherwise execute request logger.info(" MSG :{}"," OK "); return null; } return null; }}Copy the code

  • FilterType: return filterType “pre”/”route”/”post”/” error”
  • FilterOrder: Indicates the order of filters
  • If shouldFilter: is true, execute the run method
  • Run: Specific logic. In the method we get the RequestContext object, which gets the request header information and sets the return information

Next, we start the corresponding service and send the request, which returns the following message if there is no token:

Then we can implement a simple Token filtering authentication.

For enabling/disabling filters, it is not possible to modify the filter code, we can configure the filter control through the configuration file, in applicaton.yml we can configure it like this:

Zuul: # Name of the filter TokenFilter: pre: #true Disable: trueCopy the code

3.3 Request Retry

When Zuul forwarding fails, you can configure the Ribbon client to retry. The default value is false

zuul:
  retryable: trueCopy the code

3.4 Filtering sensitive Headers

When forwarding a request, HTTP headers are forwarded by default. Sometimes we do not want these headers to be forwarded, such as cookies or tokens.

zuul:
  sensitive-headers: Cookie,tokenCopy the code

3.5 Setting a Unified Prefix

zuul:
  prefix: /apiCopy the code

Four,

This chapter shares the role of Zuul components in the microservices architecture, and uses examples to realize simple filtering requests through Token. Of course, Zuul’s functions are not known here. Zuul has been tested by various Internet companies, and can perfectly integrate with the Spring Cloud ecosystem. Is an indispensable key node of microservices.

                                                                               ----END----Copy the code

In order to share this issue, you can also pay attention to the public number: programmer Xiaoxiao sheng, pay attention to more wonderful content!

SpringCloud Basics tutorial part 1 – Microservices and SpringCloud

SpringCloud basics tutorial ii – service discovery Eureka

SpringCloud basics tutorial (3)-Eureka advanced

SpringCloud Basics tutorial (4)- Getting started with configuration Center

SpringCloud basics tutorial (5)- configuring central hot availability and high availability

SpringCloud basics tutorial (6)- load balancing Ribbon

SpringCloud Basics tutorial (7)-Feign Declarative Service Invocation

Hystrix Fuse (Part 1)

Hystrix Service Monitoring (part 2)

SpringCloud basics tutorial (10)-Zull service gateway

Look forward to more exciting content…

This article is published by OpenWrite!