五、SpringCloud路由网关(zuul)

一、Zuul简介

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

Authentication
Insights
Stress Testing
Canary Testing
Dynamic Routing
Service Migration
Load Shedding
Security
Static Response handling
Active/Active traffic management

二、准备工作

创建工程service-zuul,端口8010,eureka为服务中心,前面的http://localhost:8001/eureka/,启动模块euraka-server(8001),模板模块euraka-client(启动2实例8005,8006),消费服务模块service-ribbon(8000),消费服务模块service-feign(8009),完成继续。

三、开始service-zuul工程

项目的pom.xml文件

"1.0" encoding="UTF-8"?>
"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">
    4.0.0</modelVersion>

    com.exampleId>
    service-zuul</artifactId>
    0.0.1-SNAPSHOT>
    jar</packaging>

    service-zuul>
    Demo project for Spring Boot</description>

    
        org.springframework.bootId>
        spring-boot-starter-parent</artifactId>
        1.5.9.RELEASE>
         
    </parent>

    
        UTF-8.build.sourceEncoding>
        UTF-8</project.reporting.outputEncoding>
        1.8.version>
        Edgware.RELEASE</spring-cloud.version>
    >

    
        
            org.springframework.cloud</groupId>
            spring-cloud-starter-eurekaId>
        </dependency>
        
            org.springframework.cloudId>
            spring-cloud-starter-zuul</artifactId>
        >
        
            org.springframework.boot</groupId>
            spring-boot-starter-webId>
        </dependency>

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

    
        
            
                org.springframework.boot</groupId>
                spring-boot-maven-pluginId>
            </plugin>
        >
    </build>
    
        
            
                org.springframework.cloudId>
                spring-cloud-dependencies</artifactId>
                ${spring-cloud.version}>
                pom</type>
                import>
            </dependency>
        >
    </dependencyManagement>

>

入口applicaton类加上注解@EnableZuulProxy,开启zuul的功能:

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

加上配置文件application.yml加上以下的配置代码

server:
  port: 8010
spring:
  application:
    name: service-zuul
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8001/eureka/
#路由网关转发
zuul:
  routes:
    api1:
      path: /api1/**
      serviceId: service-ribbon
    api2:
      path: /api2/**
      serviceId: service-feign

服务名为service-zuul,服务注册中心的地址为http://localhost:8001/eureka/,服务的端口为8001;以/ap1/ 开头的请求都转发给service-ribbon服务;以/api2/开头的请求都转发给service-feign服务;
打开浏览器访问:http://localhost:8010/api1/getPort;浏览器显示:

我的端口是:8006
我的端口是:8005

打开浏览器访问:http://localhost:8010/api2/getPort ;浏览器显示:

我的端口是:8006
我的端口是:8005

ok,zuul起到了路由的作用!

四、服务过滤功能

uul不仅只是路由,并且还能过滤,做一些安全验证。增加ZuulFilter过滤文件,添加功能如果请求没有携带token,则提示token为空,请求失败,有则放行,代码如下:

@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为空,请求失败");
            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返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下

pre:路由之前
routing:路由之时
post: 路由之后
error:发送错误调用
filterOrder:过滤的顺序
shouldFilter:这里可以写逻辑判断,是否要过滤,本文true,永远过滤。
run:过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。

这时访问:http://localhost:8010/api1/getPort或者http://localhost:8010/api2/getPort ;网页显示:

token为空,请求失败

再访问http://localhost:8010/api1/getPort?token=1或者http://localhost:8010/api2/getPort?token=1 ;网页显示:

我的端口是:8006
我的端口是:8005

则说明起到了过滤的功能目的!

你可能感兴趣的:(springcloud)