Spring Cloud Zuul的动态路由和动态过滤器实现(第三课)

 Zuul的作用就是路由转发和过滤, 即将请求转发到微服务或拦截请求; Zuul默认集成了负载均衡功能。架构图如下

Spring Cloud Zuul的动态路由和动态过滤器实现(第三课)_第1张图片

动态路由方案:

主应用:

    @Bean
    @RefreshScope
    @ConfigurationProperties("zuul")
    public ZuulProperties zuulProperties() {
        return new ZuulProperties();
    }

服务地址,bootstrapproperties文件如下:

spring.application.name=api-gateway
server.port=5556

#spring.cloud.config.profile=dev
spring.cloud.config.uri=http://localhost:7001/

eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

在api-gateway.properties中增加路由配置文件如下:

zuul.routes.service-a.path=/service-a/**

通过api-gateway-dynamic-route/refresh发送post刷新配置如下:

zuul.routes.service-a.path=

通过/routes发现已经修改了路由规则

动态路由器实现:

package com.didispace.filter.pre

import org.slf4j.Logger
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

class PreFilter extends ZuulFilter {

  Logger log = LoggerFactory.getLogger(PreFilter.class)

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

  @Override
  int filterOrder() {
    return 1000
  }

  @Override
  boolean shouldFilter() {
    return true
  }

  @Override
  Object run() {
    HttpServletRequest request = RequestContext.getCurrentContext().getRequest()
    log.info("this is a pre filter: Send {} request to {}", request.getMethod(), request.getRequestURL().toString())
    return null
  }

}

 

你可能感兴趣的:(微服务系列核心技术)