美文网首页
Zuul网关搭建

Zuul网关搭建

作者: 幻影翔 | 来源:发表于2020-02-12 23:24 被阅读0次

步骤

  • 建立网关模块并引入 eureka-client和zuul
  • 编写ZuulGateWayApplicaiton启动程序
  • 编写application.yml 配置eureka的server地址
  • 编写日志过滤服务 PreFilter PostFilter

效果

localhost:8000

1、pom引入

<dependencies>
        <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>
    </dependencies>

2、编写启动程序

@EnableZuulProxy
@SpringCloudApplication
public class ZuulGatewayApplicaiton {

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

3、编写application.yml

server:
  port: 9000
spring:
  application:
    name: ad-gateway
eureka:
  client:
    service-url:
      defaultZone: http://server1:8000/eureka/

4、编写日志过滤器供网关调用

@Component
@Slf4j
public class AccessLogFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER-1; // 最后执行
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        Long startTime = (Long) context.get("startTime");
        String url = request.getRequestURI(); // 请求的路径
        long duration = System.currentTimeMillis() - startTime;
        log.info("url: "+url+", duration: "+ duration / 100+ "ms");
        return null;
    }
}

相关文章

网友评论

      本文标题:Zuul网关搭建

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