Spring Cloud Zuul路由網(wǎng)關(guān)服務(wù)過(guò)濾實(shí)現(xiàn)代碼
Zuul 簡(jiǎn)介
Zuul 的主要功能是路由轉(zhuǎn)發(fā)和過(guò)濾器。路由功能是微服務(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
路由說(shuō)明:
以 /api/ribbon 開(kāi)頭的請(qǐng)求都轉(zhuǎn)發(fā)給 spring-cloud-web-admin-ribbon 服務(wù)以 /api/feign 開(kāi)頭的請(qǐng)求都轉(zhuǎn)發(fā)給 spring-cloud-web-admin-feign 服務(wù)在 Application 入口類中添加 @EnableZuulProxy 注解開(kāi)啟 zuul 功能
@SpringBootApplication@EnableEurekaClient@EnableZuulProxypublic class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); }}
配置網(wǎng)關(guān)路由失敗時(shí)的回調(diào)
創(chuàng)建 WebAdminFeignFallbackProvider 回調(diào)類
/** * 路由 hello-spring-cloud-web-admin-feign 失敗時(shí)的回調(diào) */@Componentpublic class WebAdminFeignFallbackProvider implements FallbackProvider { @Override public String getRoute() { // ServiceId,如果需要所有調(diào)用都支持回退,則 return '*' 或 return null return 'hello-spring-cloud-web-admin-feign'; } /** * 如果請(qǐng)求服務(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ù)請(qǐng)求失敗了,但是消費(fèi)者客戶端向網(wǎng)關(guān)發(fā)起的請(qǐng)求是成功的, * 不應(yīng)該把 api 的 404,500 等問(wèn)題拋給客戶端 * 網(wǎng)關(guān)和 api 服務(wù)集群對(duì)于客戶端來(lái)說(shuō)是黑盒 * @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', '無(wú)法連接');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; } }; }}
測(cè)試路由訪問(wèn)
依次運(yùn)行 EurekaApplication > ServiceAdminApplication > WebAdminRibbonApplication > WebAdminFeignApplication > ZuulApplication 各服務(wù)
訪問(wèn):http://localhost:8769/api/ribbon/hi?message=zuul
瀏覽器顯示
port : 8763,message : zuul
訪問(wèn):http://localhost:8769/api/feign/hi?message=zuul
瀏覽器顯示
port : 8763,message : zuul
至此說(shuō)明 Zuul 的路由功能配置成功。
使用 Zuul 的服務(wù)過(guò)濾功能
Zuul 不僅僅只是路由,還有很多強(qiáng)大的功能。比如用在安全驗(yàn)證方面。
創(chuàng)建服務(wù)過(guò)濾器
/** * Zuul 的服務(wù)過(guò)濾演示 */@Componentpublic class LoginFilter extends ZuulFilter { private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class); /** * 配置過(guò)濾類型,有四種不同生命周期的過(guò)濾器類型 * 1. pre:路由之前 * 2. routing:路由之時(shí) * 3. post:路由之后 * 4. error:發(fā)送錯(cuò)誤調(diào)用 * @return */ @Override public String filterType() { return 'pre'; } /** * 配置過(guò)濾的順序 * @return */ @Override public int filterOrder() { return 0; } /** * 配置是否需要過(guò)濾:true/需要,false/不需要 * @return */ @Override public boolean shouldFilter() { return true; } /** * 過(guò)濾器的具體業(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; }}
測(cè)試過(guò)濾器
訪問(wèn):http://localhost:8769/api/feign/hi?message=zuul
網(wǎng)頁(yè)顯示
Token is empty
訪問(wèn):http://localhost:8769/api/feign/hi?message=zuul&token=1
網(wǎng)頁(yè)顯示
port : 8763,message : zuul
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP.Net MVC利用NPOI導(dǎo)入導(dǎo)出Excel的示例代碼2. ThinkPHP5 通過(guò)ajax插入圖片并實(shí)時(shí)顯示(完整代碼)3. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼4. Python return語(yǔ)句如何實(shí)現(xiàn)結(jié)果返回調(diào)用5. asp文件用什么軟件編輯6. python 基于opencv 實(shí)現(xiàn)一個(gè)鼠標(biāo)繪圖小程序7. Python OpenCV實(shí)現(xiàn)測(cè)量圖片物體寬度8. 解決python執(zhí)行較大excel文件openpyxl慢問(wèn)題9. Android通過(guò)Java sdk的方式接入OpenCv的方法10. python opencv把一張圖片嵌入(疊加)到另一張圖片上的實(shí)現(xiàn)代碼
