• 第四篇:路由网关(zuul)


    一  Zuul简介

    Zuul的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如/user/**转发到到user服务,/api/**转发到到api服务。zuul默认和Ribbon结合实现了负载均衡的功能。

    二  Zuul的路由功能

    创建一个Module 叫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.hmzj</groupId>
        <artifactId>zuul</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>zuul</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.3.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>Finchley.RELEASE</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-eureka-client</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-zuul</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>

    创建application.yml

    server:
      port: 8062
    spring:
      application:
        name: zuul
    eureka:
      instance:
        prefer-ip-address: true
        instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port}
      client:
        serviceUrl:
          defaultZone: http://**:**@192.168.31.54:8060/eureka/
    zuul:
      routes:
        user: #localhost:8062/user/**中的user
          path: /user/** #转发user/下的所有请求
          serviceId: callcenter-user #服务名称
        freeswitch:
          path: /freeswitch/**
          serviceId: callcenter-freeswitch
        api:
          path: /api/**
          serviceId: callcenter-api

     其中路由部分就是routes下面的部分 

    启动服务

     

    访问http://localhost:8062/user/test/sayHello/pyq 8062是zuul的端口

     二  Zuul的过滤器功能

    在根目录下新建MyFilter.java

    package com.hmzj.zuul;
    
    import com.netflix.zuul.ZuulFilter;
    import com.netflix.zuul.context.RequestContext;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    
    import javax.servlet.http.HttpServletRequest;
    
    @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 (boolean) run();
        }
    
        @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 false;
            }
            log.info("ok");
            return true;
        }
    }

     此处通过zuul来转发服务时都要经过此过滤器

     FilterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下: 

      • pre:路由之前
      • routing:路由之时
      • post: 路由之后
      • error:发送错误调用
      • filterOrder:过滤的顺序
      • shouldFilter:这里可以写逻辑判断,是否要过滤,本文true,永远过滤。
      • run:过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。
  • 相关阅读:
    springmvc之异常处理DefaultHandlerExceptionResolver
    springmvc之异常处理ResponseStatusExceptionResolver
    springmvc之异常处理中ExceptionHanderExceptionResolver
    springmvc之多个拦截器方法执行的顺序
    springmvc之配置拦截器拦截相应的请求
    springmvc之自定义拦截器
    springmvc之文件上传
    springmvc之HttpMessageConverter<T>
    构建Java并发模型框架
    Java线程:线程的调度-守护线程——Java线程:线程的调度-合并——Java线程:新特征-障碍器——Java线程:大总结
  • 原文地址:https://www.cnblogs.com/pangyangqi/p/9391502.html
Copyright © 2020-2023  润新知