Spring Cloud Zuul路由網(wǎng)關(guān)服務(wù)過濾實(shí)現(xiàn)代碼
Zuul 簡介
Zuul 的主要功能是路由轉(zhuǎn)發(fā)和過濾器。路由功能是微服務(wù)的一部分,比如 /api/admin 轉(zhuǎn)發(fā)到到 Admin 服務(wù),/api/member 轉(zhuǎn)發(fā)到到 Member 服務(wù)。Zuul 默認(rèn)和 Ribbon 結(jié)合實(shí)現(xiàn)了負(fù)載均衡的功能。
引入依賴
在 pom.xml 中主要添加 spring-cloud-starter-netflix-eureka-server 和 spring-cloud-starter-netflix-zuul 依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId></dependency>
相關(guān)配置
在 application.yml 中主要添加 Zuul 路由配置
zuul: routes: api-a: path: /api/ribbon/** serviceId: hello-spring-cloud-web-admin-ribbon api-b: path: /api/feign/** serviceId: hello-spring-cloud-web-admin-feign
路由說明:
以 /api/ribbon 開頭的請求都轉(zhuǎn)發(fā)給 spring-cloud-web-admin-ribbon 服務(wù)以 /api/feign 開頭的請求都轉(zhuǎn)發(fā)給 spring-cloud-web-admin-feign 服務(wù)在 Application 入口類中添加 @EnableZuulProxy 注解開啟 zuul 功能
@SpringBootApplication@EnableEurekaClient@EnableZuulProxypublic class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); }}
配置網(wǎng)關(guān)路由失敗時的回調(diào)
創(chuàng)建 WebAdminFeignFallbackProvider 回調(diào)類
/** * 路由 hello-spring-cloud-web-admin-feign 失敗時的回調(diào) */@Componentpublic class WebAdminFeignFallbackProvider implements FallbackProvider { @Override public String getRoute() { // ServiceId,如果需要所有調(diào)用都支持回退,則 return '*' 或 return null return 'hello-spring-cloud-web-admin-feign'; } /** * 如果請求服務(wù)失敗,則返回指定的信息給調(diào)用者 * @param route * @param cause * @return */ @Override public ClientHttpResponse fallbackResponse(String route, Throwable cause) { return new ClientHttpResponse() { /** * 網(wǎng)關(guān)向 api 服務(wù)請求失敗了,但是消費(fèi)者客戶端向網(wǎng)關(guān)發(fā)起的請求是成功的, * 不應(yīng)該把 api 的 404,500 等問題拋給客戶端 * 網(wǎng)關(guān)和 api 服務(wù)集群對于客戶端來說是黑盒 * @return * @throws IOException */ @Override public HttpStatus getStatusCode() throws IOException {return HttpStatus.OK; } @Override public int getRawStatusCode() throws IOException {return HttpStatus.OK.value(); } @Override public String getStatusText() throws IOException {return HttpStatus.OK.getReasonPhrase(); } @Override public void close() { } @Override public InputStream getBody() throws IOException {ObjectMapper objectMapper = new ObjectMapper();Map<String, Object> map = new HashMap<>();map.put('status', 200);map.put('message', '無法連接');return new ByteArrayInputStream(objectMapper.writeValueAsString(map).getBytes('UTF-8')); } @Override public HttpHeaders getHeaders() {HttpHeaders headers = new HttpHeaders();// 和 getBody 中的內(nèi)容編碼一致headers.setContentType(MediaType.APPLICATION_JSON_UTF8);return headers; } }; }}
測試路由訪問
依次運(yùn)行 EurekaApplication > ServiceAdminApplication > WebAdminRibbonApplication > WebAdminFeignApplication > ZuulApplication 各服務(wù)
訪問:http://localhost:8769/api/ribbon/hi?message=zuul
瀏覽器顯示
port : 8763,message : zuul
訪問:http://localhost:8769/api/feign/hi?message=zuul
瀏覽器顯示
port : 8763,message : zuul
至此說明 Zuul 的路由功能配置成功。
使用 Zuul 的服務(wù)過濾功能
Zuul 不僅僅只是路由,還有很多強(qiáng)大的功能。比如用在安全驗(yàn)證方面。
創(chuàng)建服務(wù)過濾器
/** * Zuul 的服務(wù)過濾演示 */@Componentpublic class LoginFilter extends ZuulFilter { private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class); /** * 配置過濾類型,有四種不同生命周期的過濾器類型 * 1. pre:路由之前 * 2. routing:路由之時 * 3. post:路由之后 * 4. error:發(fā)送錯誤調(diào)用 * @return */ @Override public String filterType() { return 'pre'; } /** * 配置過濾的順序 * @return */ @Override public int filterOrder() { return 0; } /** * 配置是否需要過濾:true/需要,false/不需要 * @return */ @Override public boolean shouldFilter() { return true; } /** * 過濾器的具體業(yè)務(wù)代碼 * @return * @throws ZuulException */ @Override public Object run() throws ZuulException { RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); String token = request.getParameter('token'); if (token == null) { logger.warn('Token is empty'); context.setSendZuulResponse(false); context.setResponseStatusCode(401); try {context.getResponse().getWriter().write('Token is empty'); } catch (IOException e) { } } else { logger.info('OK'); } return null; }}
測試過濾器
訪問:http://localhost:8769/api/feign/hi?message=zuul
網(wǎng)頁顯示
Token is empty
訪問:http://localhost:8769/api/feign/hi?message=zuul&token=1
網(wǎng)頁顯示
port : 8763,message : zuul
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. chat.asp聊天程序的編寫方法2. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫的方法3. XML入門的常見問題(二)4. Jsp中request的3個基礎(chǔ)實(shí)踐5. JavaScrip簡單數(shù)據(jù)類型隱式轉(zhuǎn)換的實(shí)現(xiàn)6. 得到XML文檔大小的方法7. ASP.NET Core實(shí)現(xiàn)中間件的幾種方式8. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能9. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)10. 如何在jsp界面中插入圖片
