路由网关---zuul

作者: dalaoyang | 来源:发表于2018-04-22 13:38 被阅读303次

    Zuul:Zuul 是在云平台上提供动态路由,监控,弹性,安全等边缘服务的框架。Zuul 相当于是设备和 Netflix 流应用的 Web 网站后端所有请求的前门。

    在微服务盛行的时代,客户端与系统之间的交互基本上如下图:

    image

    客户端想要请求到服务,首先请求到zuul网关,然后zuul网管将请求分发到对应的服务去。

    新建一个springcloud_zuul(8766),pom文件加入zuul依赖,pom文件完整代码如下:

    <?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>
    

    然后在启动类上添加@EnableZuulProxy启动zuul,完整代码如下:

    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);
        }
    
    }
    
    

    在配置文件加入如下配置:

    ##端口号
    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
    
    

    然后分别启动之前service(8762),service_ribbon(8764)和springcloud_zuul(8766)。

    先看一下http://eureka.dalaoyang.cn,如下:

    image

    然后在浏览器上分别访问http://localhost:8766/service-a,如下

    image

    http://localhost:8766/service-b,如下

    image

    zuul网关的简单配置到这里基本上完成了。

    然后介绍一个zuul的过滤器,新建一个过滤器的类RequestLogFilter,这个类需要继承ZuulFilter,需要实现几个方法。

    filterType:这个方法返回过滤器的类型,pre(路由前执行),route(路由中执行),post(路由后执行),error(发生错误后执行)

    filterOrder:返回一个int来指定过滤器的执行顺序

    shouldFilter:返回boolean值来决定过滤器是否执行,true执行,false不执行。

    run:过滤器要执行的操作。

    本项目中过滤器代码如下:

    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 yangyang@dalaoyang.cn
     * @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;
        }
    }
    

    修改一下启动类:

    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,然后看控制台可以看到如下图:

    image

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

    image

    那么在访问,就会无法转发,其实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 yangyang@dalaoyang.cn
     * @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如下图所示:

    image

    源码下载 :大老杨码云

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

    相关文章

      网友评论

        本文标题:路由网关---zuul

        本文链接:https://www.haomeiwen.com/subject/jztclftx.html