SpringCloud (Finchley version) Tutorial (E): Routing Gateway (zuul)

In the micro-service architecture, service management requires several basic components, including registration and service discovery, service consumption, load balancing, circuit breakers, intelligent routing, configuration management, mutual cooperation of these basic components, jointly set up a simple micro-service system.

Note: A and B services are services that can be invoked from each other, plotting the time forgotten. And configure the service is registered with the service registry.

In Spring Cloud micro-services system, a common load balancing methods, the client request first passes through load balancing (zuul, Ngnix), and then reach the service gateway (zuul cluster), and then to a specific service. , Unified registration services to highly available cluster service registry, all configuration files by the configuration service management services (under article describes), configure service profiles on the git repository to facilitate developers to change the configuration at any time.

A, Zuul Introduction
The main function of Zuul is routing forwarding and filters. Routing function is part of the micro-services, such as / api / user is forwarded to the service to the user, / api / shop to shop forwarded to the service. zuul default and Ribbon combination to achieve a load balancing feature.

zuul has the following features:

Authentication
Insights
Stress Testing
Canary Testing
Dynamic Routing
Service Migration
the Load Shedding
Security
Static the Response Handling
the Active / traffic the Active Management
Second, prepare for work
to continue to use on a project. In the original project, create a new project.

Third, create a service-zuul project
its pom.xml file 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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.liu.example</groupId>
    <artifactId>service-zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>service-zuul</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-netflix-eureka-client</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>${spring-cloud.version}</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>

</project>

At its inlet applicaton class annotate @EnableZuulProxy, open zuul features:

package com.liu.example.servicezuul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
@EnableZuulProxy
public class ServiceZuulApplication {

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

Plus profiles application.yml add 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
  host:
    connect-timeout-millis: 3000
    socket-timeout-millis: 3000

ribbon:
  ReadTimeout: 3000
  ConnectTimeout: 3000

hystrix:
    command:
        default:
            execution:
                isolation:
                    thread:
                        timeout-in-milliseconds: 3000

First registered address designated service center is http: // localhost: 8761 / eureka /, port services for 8769, the service name service-zuul; to request / api-a / the beginning are forwarded to the service-ribbon service; to / api-b / requests are forwarded to the beginning of the service-feign services;

This in turn runs five engineering; opening a browser: http: // localhost:? 8769 / api-a / hi name = forezp; browser shows:

! Hello my port number is: 8762

Open your browser and visit: http: // localhost: 8769 / api-b / hi name = forezp; browsers display?:

! Hello my port number is: 8762

This shows zuul played a role in routing

Fourth, the service filter
zuul not just routing, and also filter and do some safety validation. Continued renovation project, the new MyFilter;

Package com.liu.example.servicezuul; 

Import com.netflix.zuul.ZuulFilter;
 Import com.netflix.zuul.context.RequestContext;
 Import org.slf4j.Logger;
 Import org.slf4j.LoggerFactory;
 Import org.springframework.stereotype. the Component; 

Import the javax.servlet.http.HttpServletRequest; 

@Component 
public  class the MyFilter the extends ZuulFilter { 

    Private  static Logger LoggerFactory.getLogger = log (the MyFilter. class ); 

    / ** 
     * pre: before the route 
     * routing: the routing 
     * post: after routing 
     * error: send error calling
     * 
     * DETAILED logic filter. Available are complex, including check sql, nosql in the end to determine whether the request has no access.@return 
     * / 
    @Override 
    public String filterType () {
         return "pre" ; 
    } 

    / ** 
     * Sort 
     * @return 
     * / 
    @Override 
    public  int filterOrder () {
         return 0 ; 
    } 

    / ** 
     * here write logic, whether to filter paper true, forever filtration. 
     * @Return 
     * / 
    @Override 
    public  Boolean shouldFilter () {
         return  to true ; 
    } 

    / ** 
     * @return 
     * / 
    @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 representative of the type of filter, the filter type defines four different zuul in the life cycle, as follows:
Before route: pre
routing: when the route
after the route: POST
error: Error sending call
filterOrder: filtered order
shouldFilter: here you can write logic to determine whether to filter, this true, forever filtration.
run: the specified logical filter. Available are complex, including check sql, nosql in the end to determine whether the request has no access.
Then visit: http: // localhost: 8769 / api-a / hi name = forezp; page display?:

token is empty

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

! Hello my port number is: 8762

Download this article Source:
https://github.com/MrLiu1227/MySpringCloud.git

Guess you like

Origin www.cnblogs.com/liuyuan1227/p/11220295.html