用springboot+zuul做一个网关

本人微信 zf363133213 欢迎各位添加好友,共同探讨问题

业务:主要是做一个灰度的网关,请求头target为1时走http://localhost:9090/test/的灰度版本

           其他走http://localhost:8080/test/ 的生产版本

1 创建springboot项目

2 在pom.xml加入


    org.springframework.cloud
    spring-cloud-starter-zuul
    1.4.6.RELEASE

3 application.properties中

zuul.host.socket-timeout-millis=60000

zuul.host.connect-timeout-millis=10000

zuul.routes.test.url=http://localhost:8080/test/

zuul.routes.test.path=/test/**

zuul.routes.gray.url=http://localhost:9090/test/

4  启动类上加注解@EnableZuulProxy

5 网关实体类

@Component

public class GrayFilter extends ZuulFilter{

@Autowired

private Environment environment;

@Overfide

public boolean shouldFilter(){

//获取当前request,获得请求头中的target,如果这个方法返回false,下面的run()方法将不会执行

HttpServletRequest request = RequestContext.getCurrentContext().getRequest();

return null != request.getHeader("target");

}

@Override

public Object run(){

HttpServletRequest request = RequestContext.getCurrentContext().getRequest();

String target = request.getHeader("target");

if("target".equals(target)){

try{

RequestContext.RequestContext.getCurrentContext().setRouteHost(new URL(environment.getProperty("zuul.routes.gray.url")));

} catch (Exception e){

}

}

return null;

}

@Override

public String filterType(){

return FilterConstants.ROUTE_TYPE;

}

@Override

public int filterOrder(){

return FilterConstants.SIMPLE_HOST_ROUTING_FILTER_ORDER-1;

}

}

你可能感兴趣的:(用springboot+zuul做一个网关)