API Gateway Services in Spring Cloud zuul__spring

Source: Internet
Author: User
Tags response code

So far, we have introduced a lot of the content of Spring cloud, Ribbon, Hystrix, feign the knowledge that everyone is familiar with, we also mentioned in the previous micro-service is to split a large project into a number of small independent modules, And then through service management let these independent modules work together. So let's think about this. Two questions: 1. If there are many independent services in my micro-service that have to be serviced externally, how will the developer or the operator manage these interfaces? Especially when the project is very large and very complex how to manage? 2. Authority management is also a commonplace issue, In a micro-service, a separate system is broken down into a number of separate modules, and in order to ensure security, do I need to add the same authentication code on each module to ensure that the system is not illegally accessed? If this is the case, then the workload is too large, and maintenance is very inconvenient.

To solve the problem mentioned above, we introduced the concept of API gateway, API Gateway is a more intelligent application server, it is similar to our micro-service architecture system façade, all external access to the API Gateway first, and then the API gateway to achieve request routing, load balancing, authorization and other functions. The spring Cloud Zuul provided in spring Cloud implements the functionality of the API gateway, so let's take a look at a basic use of spring Cloud Zuul.

This is the 19th article in the Spring Cloud series that will help you better understand this article by understanding the first 18 articles:

1. Use spring Cloud to build service registration center
2. Use spring cloud to build a highly available service registration center
Discovery and consumption of service in 3.Spring cloud
The core concept in 4.Eureka
5. What is client load balancing
Several common request methods in 6.Spring Resttemplate
The reverse route of 7.RestTemplate, from sending requests to load balancing
Overview of Load balancers in 8.Spring cloud
Load balancing strategy in 9.Spring Cloud
Hystrix of circuit breaker in 10.Spring Cloud
11.Spring Cloud Custom Hystrix Request command
Service demotion and exception handling of Hystrix in 12.Spring cloud
Request caching for Hystrix in 13.Spring Cloud
Hystrix request merging in the 14.Spring cloud
Hystrix instrument panel and turbine cluster monitoring in 15.Spring cloud
Declarative service invocation in 16.Spring cloud feign
Inheritance characteristics of feign in 17.Spring cloud
Feign configuration in 18.Spring cloud construction Gateway

The architecture of the gateway is implemented through the following three steps. 1. Create the Spring boot project and add dependencies

First we create an ordinary spring boot project named Api-gateway, and then add dependent dependencies, Here we mainly add two dependent Spring-cloud-starter-zuul and Spring-cloud-starter-eureka,spring-cloud-starter-zuul dependencies that contain ribbon, Hystrix, actuator, etc., as follows:

<parent> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-parent</artifactid> <version>1.5.7.RELEASE</version> <relativePath/> <!--lookup parent from repository--> </parent> <properties> <project.build.sourceencoding>ut F-8</project.build.sourceencoding> <project.reporting.outputencoding>utf-8</ Project.reporting.outputencoding> <java.version>1.8</java.version> <spring-cloud.version> dalston.sr3</spring-cloud.version> </properties> <dependencies> <dependency> <group Id>org.springframework.boot</groupid> <artifactId>spring-boot-starter</artifactId> </d ependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifact Id>spring-cloud-starter-zuul</artifactid> </dependency> &LT;dependency> <groupId>org.springframework.cloud</groupId> <artifactid>spring-cloud-s tarter-eureka</artifactid> </dependency> </dependencies> <dependencyManagement> <depend Encies> <dependency> <groupId>org.springframework.cloud</groupId> ;artifactid>spring-cloud-dependencies</artifactid> <version>${spring-cloud.version}</version
    > <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
2. Add Annotations

Then add the @enablezuulproxy annotation on the entry class to represent the API Gateway service function that opens the Zuul, as follows:

@SpringBootApplication
@EnableZuulProxy Public
class Apigatewayapplication {public

    static void main ( String[] args) {
        springapplication.run (apigatewayapplication.class, args);
    }
}
3. Configure Routing Rules

The configuration in the Application.properties file can be divided into two parts, one part is the basic information of the Zuul application, and the other is the routing rule, as follows:

# Basic Information Configuration
spring.application.name=api-gateway
server.port=2006
# Routing rule configuration
zuul.routes.api-a.path= /api-a/**
Zuul.routes.api-a.serviceid=feign-consumer

# API Gateway will also be registered as a service to the Eureka-server
eureka.client.service-url.defaultzone=http://localhost:1111/eureka/

We've configured the routing rules here. All/api-a/** requests will be forwarded to the Feign-consumer service, and the Feign-consumer service address is analyzed by eureka-server. We only need to write the service name here. Take the above configuration as an example, if I request the Http://localhost:2006/api-a/hello1 interface is equivalent to requesting http://localhost:2005/hello1 (my feign-consumer address here is HTTP ://localhost:2005), the api-a that we configure in the routing rule is the name of the route, which can be defined arbitrarily, but the routing name of a set of path and Serviceid mappings is the same.

OK, after doing this, we start our eureka-server, provider, and Feign-consumer, then visit the following address Http://localhost:2006/api-a/hello1, and the results are as follows:

Seeing this effect shows that our API Gateway service has been built successfully, and the requests that we send to meet the routing rules are automatically forwarded to the corresponding service for processing. Request Filtering

Building the gateway, let's take a look at how the gateway can be used to implement a simple permission validation. This involves another core feature of Spring Cloud Zuul: request filtering. Request filtering is somewhat similar to the Java filter filter, where all requests are intercepted and then processed differently depending on the locale, so let's take a look at how the filters in the Zuul are used. Very simple, two steps: 1. Define Filter

First we define a filter to inherit from Zuulfilter, as follows:

public class Permisfilter extends Zuulfilter {
    @Override public
    String FilterType () {return
        "pre";
    }

    @Override public
    int Filterorder () {return
        0;
    }

    @Override Public
    Boolean shouldfilter () {
        true;
    }

    @Override public
    Object run () {
        RequestContext ctx = Requestcontext.getcurrentcontext ();
        HttpServletRequest request = Ctx.getrequest ();
        String login = request.getparameter ("login");
        if (login = = null) {
            ctx.setsendzuulresponse (false);
            Ctx.setresponsestatuscode (401);
            Ctx.addzuulresponseheader ("Content-type", "Text/html;charset=utf-8");
            Ctx.setresponsebody ("illegal access");
        }
        return null;
    }
}

On this class I say the following points:

The return value of the 1.filterType method is the type of the filter, and the type of filter determines which lifecycle the filter executes, the pre indicates that the filter is executed before the route, and other optional values are post, error, route, and Static, and of course can be customized.
The 2.filterOrder method represents the order in which filters are executed, and this method makes sense when filters are many.
The 3.shouldFilter method is used to determine whether the filter executes, true for execution, false for no execution, and in actual development, we can decide to filter the address based on the current request address, where I return true directly.
The 4.run method indicates the specific logic of the filter, assuming that the login parameter is carried in the request address, it is considered to be a legitimate request, otherwise it is an illegal request, if it is an illegal request, first set Ctx.setsendzuulresponse (false); Indicates that the request is not routed, and then the response code and response value are set. The return value of this run method has no meaning temporarily in the current version (DALSTON.SR3) and can return any value. 2. Configure Filter Bean

You can then configure the relevant beans in the entry class, as follows:

@Bean
permisfilter Permisfilter () {return
    new Permisfilter ();
}

At this point, if we visit http://localhost:2006/api-a/hello1, the result is as follows:

If you add the login parameter to the request address, the result is as follows:

Summary

Here, the small partners should have seen the strength of spring Cloud Zuul, the API gateway as a unified portal of the system, the micro-services in the internal details are shielded, and can automatically maintain service instances, load-balanced routing forwarding, while, It provides filters for all micro services to provide a unified authority to check the mechanism, so that the service itself only need to focus on business logic.

Zuul the introduction of the knowledge we first introduced here, the small partners have questions to welcome the message discussion.

Resources:

1. Spring Cloud Micro Service

For more Java EE information please pay attention to the public number:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.