Routing gateway---zuul

Zuul: Zuul is a framework for providing dynamic routing, monitoring, elasticity, security and other edge services on cloud platforms. Zuul is equivalent to being the front door for all requests to the backend of the web site on the device and the Netflix streaming app.

In the era of microservices, the interaction between the client and the system is basically as follows:

If the client wants to request a service, it first requests the zuul gateway, and then the zuul network management distributes the request to the corresponding service.

Create a new springcloud_zuul (8766), add the zuul dependency to the pom file, and the complete code of the pom file is 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.dalaoyang</groupId>
    <artifactId>springcloud_zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springcloud_zuul</name>
    <description>springcloud_zuul</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.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>
        <spring-cloud.version>Edgware.SR1</spring-cloud.version>
    </properties>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </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>

Then add @EnableZuulProxy to the startup class to start zuul, the complete code is as follows:

package com.dalaoyang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableZuulProxy
public class SpringcloudZuulApplication {

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

}

Add the following configuration to the configuration file:

##端口号
server.port=8766

##服务名称
spring.application.name=service-zuul

##注册中心地址
eureka.client.service-url.defaultZone=http://eureka.dalaoyang.cn/eureka/


##zuul路由转发 service-a转发到service_ribbon
zuul.routes.service-a.path=/service-a/**

zuul.routes.service-a.service-id=service_ribbon

##zuul路由转发 service-b转发到service
zuul.routes.service-b.path=/service-b/**

zuul.routes.service-b.service-id=service

Then start the previous service (8762), service_ribbon (8764) and springcloud_zuul (8766) respectively.

Take a look at http://eureka.dalaoyang.cn first , as follows:

Then visit http://localhost:8766/service-a on the browser respectively , as follows

http://localhost:8766/service-b , as follows

The simple configuration of the zuul gateway is basically completed here.

Then introduce a zuul filter, create a new filter class RequestLogFilter, this class needs to inherit ZuulFilter, and needs to implement several methods.

filterType: This method returns the type of filter, pre (execute before routing), route (execute in routing), post (execute after routing), error (execute after error)

filterOrder: Returns an int to specify the order in which the filters are executed

shouldFilter: Returns a boolean value to determine whether the filter is executed, true executes, false does not execute.

run: The action to be performed by the filter.

The filter code in this project is as follows:

package com.dalaoyang.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;


/**
 * @author dalaoyang
 * @Description
 * @project springcloud_learn
 * @package com.dalaoyang.filter
 * @email [email protected]
 * @date 2018/4/22
 */
public class RequestLogFilter extends ZuulFilter {

    Logger logger = LoggerFactory.getLogger(RequestLogFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

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

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest httpServletRequest = requestContext.getRequest();
        logger.info("请求路径:"+httpServletRequest.getRequestURL().toString());
        return null;
    }
}

Modify the startup class:

package com.dalaoyang;

import com.dalaoyang.filter.RequestLogFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableZuulProxy
public class SpringcloudZuulApplication {

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

    @Bean
    public RequestLogFilter requestLogFilter(){
        return new RequestLogFilter();
    }
}

在重启项目,访问http://localhost:8766/service-a,然后看控制台可以看到如下图:

有时会出现这样的情况,比如本文的service实例down了,如下图这种情况

那么在访问,就会无法转发,其实zuul也提供了失败回调的方法。
新建一个ServiceFallback类实现ZuulFallbackProvider接口,需要重写2个方法。

其中getRoute方法中可以指定为哪个微服务回退,*为所有服务。

代码如下:

package com.dalaoyang.fallback;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @author dalaoyang
 * @Description
 * @project springcloud_learn
 * @package com.dalaoyang.fallback
 * @email [email protected]
 * @date 2018/4/22
 */
@Component
public class ServiceFallback implements ZuulFallbackProvider {

    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("当前访问服务不可用!".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                MediaType mediaType = new MediaType("application", "json",
                        Charset.forName("UTF-8"));
                httpHeaders.setContentType(mediaType);
                return httpHeaders;
            }
        };
    }
}

重启项目,访问http://localhost:8766/service-a如下图所示:

源码下载 :大老杨码云

个人网站:https://www.dalaoyang.cn

Guess you like

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