spring cloud学习(四) 动态路由

Zuul的主要功能是路由和过滤器。路由功能是微服务的一部分,zuul实现了负载均衡。

1.1
新建模块zuul
pom.xml

<?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">
    <parent>
        <artifactId>spring-cloud</artifactId>
        <groupId>com.feng</groupId>
        <version>0.0.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>zuul</artifactId>

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

</project>

1.2
application.yml:

spring:
  application:
    name: zuul

server:
  port: 8020

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8010/eureka/

zuul:
  routes:
    api-a:
      path: /service-a/**
      serviceId: service-a
    api-b:
      path: /service-b/**
      serviceId: service-b
  sensitive-headers:  #设置忽略的头信息,设置为空能解决会话保持问题
  add-host-header: true #设为true才能保持Host头信息处理正确

上面配置说明把/service-a/开头的所有请求都转发给service-a服务执行,把/service-b/开头的所有请求都转发给service-b服务执行

1.3
ZuulApplication,使用EnableZuulProxy注解开启zuul功能,并且注册了一个zuul的过滤器

/**
 * @author fengzp
 * @date 17/4/27
 * @email fengzp@gzyitop.com
 * @company 广州易站通计算机科技有限公司
 */
@SpringCloudApplication //这个注解整合了@SpringBootApplication、@EnableDiscoveryClient、@EnableCircuitBreake
@EnableZuulProxy
public class ZuulApplication {

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

    @Bean
    public MyZuulFilter getZuulFilter(){
        return new MyZuulFilter();
    }
}

MyZuulFilter,过滤器加了个判断id是否为空,空则返回401错误码

public class MyZuulFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyZuulFilter.class);

    /**
     * 返回过滤器类型
     * @return
     *  pre:可以在请求被路由之前调用
     *  routing:在路由请求时候被调用
     *  post:在routing和error过滤器之后被调用
     *  error:处理请求时发生错误时被调用
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 通过int值来定义过滤器的执行顺序
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断过滤器是否执行
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑
     *  ctx.setSendZuulResponse(false)令zuul不允许请求,
     *  ctx.setResponseStatusCode(401)设置了其返回的错误码
     *  ctx.setResponseBody(body)编辑返回body内容
     * @return
     */
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest request = ctx.getRequest();

        log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("id");
        if(accessToken == null) {
            log.warn("id is null");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }

        log.info("pass!");
        return null;
    }

}

1.4

把之前负载的service-b的spring.application.name改为service-b, 运行项目,分别打开http://localhost:8020/service-a/hi?id=zuul和http://localhost:8020/service-b/hi?id=zuul


posted @ 2017-05-09 17:32  fengzp  阅读(5072)  评论(0编辑  收藏  举报