SringCloud | Part 5: Routing Gateway (zuul) (Route Forwarding and Filtering)

In the microservice architecture, several basic service governance 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 short-answer microservice system is shown in the following figure:



Note: A service and B service can call each other, and I forgot 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 goes through load balancing (zuul, Ngnix), then reaches the service gateway (zuul cluster), and then goes to the specific service. , the service is uniformly registered to the high-availability service registry cluster, and all the configuration files of the service are managed by the configuration service (described in the next article), and the configuration files of the configuration service are placed in the git repository, which is convenient for developers to change the configuration at any time.

1. Introduction
to Zuul The main functions of Zuul are routing forwarding and filtering. The routing function is part of the microservice, such as /api/user is forwarded to the user service, and /api/shop is forwarded to the shop service. By default, zuul is combined 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

Second, preparations
Continue to use the project in the previous section. Create a new project on top of the original project. 3. Create the pom.xml file of the

service-zuul project 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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RC1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>


Add the annotation @EnableZuulProxy to its entry applicaton class to enable the function of zuul:

@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ServiceZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceZuulApplication.class, args);
    }
}


Plus the configuration file application.yml plus 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 registry as http://localhost:8761/eureka/, the port of the service is 8769, and the service name is service-zuul; requests starting with /api-a/ are forwarded to the service-ribbon service; The requests starting with /api-b/ are forwarded to the service-feign service;

run these five projects in sequence; open the browser to access: 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 has played a role The role of routing

4.
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 the filter. Four filter types with different life cycles are defined in zuul, as follows:
pre: before routing: before
routing:
post when routing: after routing
error: send an error to call
filterOrder: The order of filtering
shouldFilter: Here you can write a logical judgment, whether to filter, this article is true, and filter forever.
run: The specific logic of the filter. The availability is very complicated, including checking sql and nosql to determine whether the request has permission to access.
At this time, visit: http://localhost:8769/api-a/hi?name=forezp ; the webpage displays:

token is empty

Visit http://localhost:8769/api-a/hi?name=forezp&token=22 ;
webpage Display:

hi forezp,i am from port:8762Reposted

from: http://blog.csdn.net/forezp/article/details/69939114

















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326232308&siteId=291194637