1、簡介git
在Springcloud中用zuul來實現網關功能,客戶端的請求首先通過負載均衡Ngnix,再到達服務網關(zuul集羣),而後再到具體的服務。Zuul的主要功能是路由轉發和過濾器。路由功能是微服務的一部分,好比/api/server1轉發到到server1服務。zuul默認和Ribbon結合實現了負載均衡的功能。願意瞭解源碼的朋友直接求求交流分享技術:二一四七七七五六三三 github
2、搭建web
首先是POM文件 spring
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
而後在applicaton類加上註解@EnableZuulProxy,開啓zuul的功能 api
@SpringBootApplication @EnableZuulProxy @EnableEurekaClient @RefreshScope public class HfzZuulApplication { public static void main(String[] args) { SpringApplication.run(HfzZuulApplication.class, args); } }
yml配置以下 安全
eureka: client: serviceUrl: defaultZone: http://name:pass@IP/eureka/ instance: ip-address: Ip地址 prefer-ip-address: true server: port: 8769 spring: application: name: service-zuul sleuth: sampler: percentage: 1.0 cloud: config: discovery: enabled: true service-id: CONFIG-SERVER label: master profile: dev name: hfz-zuul username: name password: pass
以上是在項目中配置的,爲了使項目更加靈活,因此將路由的配置放在github上,這樣能夠動態讀取 架構
zuul: routes: api-a: path: /api-a/** serviceId: service-ribbon api-b: path: /api-b/** serviceId: service-feign
以/api-a/ 開頭的請求都轉發給service-ribbon服務;以/api-b/開頭的請求都轉發給service-feign服務; app
3、服務過濾負載均衡
zuul不只能夠路由,而且還能經過過濾來攔截一些服務,能夠用來作安全驗證。 ide
public class MyFilter extends ZuulFilter{ private static Logger log = LoggerFactory.getLogger(MyFilter.class); @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString())); Object accessToken = request.getParameter("token"); if(accessToken == null) { log.warn("token is empty"); ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(401); try { ctx.getResponse().getWriter().write("token is empty"); }catch (Exception e){} return null; } log.info("ok"); return null; } }
filterType:返回一個字符串表明過濾器的類型,在zuul中定義了四種不一樣生命週期的過濾器類型,具體以下:
pre:路由以前
routing:路由之時
post: 路由以後
error:發送錯誤調用
filterOrder:過濾的順序
shouldFilter:邏輯判斷,是否要過濾
run:過濾器的具體邏輯控制
接下來就能夠測試訪問了。
技術架構圖以下: