-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Labels
Description
路由网关zuul
zuul
- 路由转发
- 过滤器
- 默认与ribbon实现负载均衡
服务路由
-
新建工程eurekazuul,在pom中增加zuul的起步依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency>
-
在application启动类中添加注解@ EnableZuulProxy,开启zuul
@SpringBootApplication @EnableZuulProxy @EnableEurekaClient @EnableDiscoveryClient public class EurekazuulApplication { public static void main(String[] args) { SpringApplication.run(EurekazuulApplication.class, args); } }
-
配置文件
server.port=8666 spring.application.name=eurekazuul eureka.client.serviceUrl.defaultZone=http://localhost:8767/eureka/ zuul.routes.api-a.path=/api-a/** zuul.routes.api-a.service-id=eurekaribbon zuul.routes.api-b.path=/api-b/** zuul.routes.api-b.service-id=eurekafeign
服务端口为8666,注册中心端口仍为8767
以/api-a/ 开头的请求都转发给eurekaribbon服务;以/api-b/开头的请求都转发给eurekafeign服务 -
分别启动以下服务:
- eurekaserver:8767
- eurekaclient:8662
- eurekaclient:8664
- eurekaribbon:8661
- eurekafeign:8665
- eurekazuul:8666
-
不断请求http://localhost:8666/api-a/b?name=huge ,zuul路由触发,返回如下结果:
hello huge ,port:8662
hello huge ,port:8664不断请求http://localhost:8666/api-b/feign?name=huget ,zuul路由触发,返回如下结果:
hello huget ,port:8664
hello huget ,port:8662
服务过滤
zuul有过滤功能,可以做一些安全验证
-
在以上工程继续改造使用
-
new一个类,继承
ZuulFilter@Component public class ServiceFilter extends ZuulFilter { @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); Object accessToken = request.getParameter("token"); if (accessToken == null) { context.setSendZuulResponse(false); context.setResponseStatusCode(401); try { context.getResponse().getWriter().write("error:token is empty"); } catch (IOException e) { e.printStackTrace(); } return null; } return null; } }
继承需实现以下方法
filterType过滤器类型,在zuul中定义了四种不同生命周期的过滤器类型:- pre:在请求被路由之前调用
- route:在路由请求时候被调用
- error:处理请求时发生错误时被调用
- post:在route和error过滤器之后被调用
filterOrder过滤器优先级,定义过滤器执行的顺序,数字越大,优先级越低shouldFilter过滤器开关,判断该过滤器是否要执行run过滤器具体逻辑
-
访问http://localhost:8666/api-b/feign?name=huget ,返回结果
error:token is empty
访问http://localhost:8666/api-b/feign?name=huget&token=lala ,返回结果:
hello huget ,port:8662
Reactions are currently unavailable