如何在springboot中使用zuul實現(xiàn)網(wǎng)關(guān)?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
創(chuàng)新互聯(lián)于2013年開始,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項目網(wǎng)站建設(shè)、網(wǎng)站設(shè)計網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元墾利做網(wǎng)站,已為上家服務(wù),為墾利各地企業(yè)和個人服務(wù),聯(lián)系電話:18980820575
1 添加依賴
dependencies { implementation('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') implementation('org.springframework.cloud:spring-cloud-starter-netflix-zuul') testImplementation('org.springframework.boot:spring-boot-starter-test') implementation('com.marcosbarbero.cloud:spring-cloud-zuul-ratelimit:1.3.2.RELEASE') }
2 添加yml
server: port: 8300 spring: application: name: microservice-gateway-zuul eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:6761/eureka instance: ip-address: true zuul: routes: users: path: /lind/** #以lind開頭的路徑被重定向到lind服務(wù) serviceId: lind add-host-header: true #顯示真實的http頭 retryable: false #關(guān)閉Hystrix的重試功能 ratelimit: enabled: true # repository: redis behind-proxy: true policies: users: limit: 5 #限流,每分鐘請求5次 refresh-interval: 60 type: - user - origin - url # url類型的限流就是通過請求路徑區(qū)分 # origin是通過客戶端IP地址區(qū)分 # user是通過授權(quán)用戶進行區(qū)分,也包括匿名用戶
3 添加實現(xiàn)代碼
http攔截器,獲取用戶ID,為子服務(wù)進行傳遞
public class PreRequestLogFilter extends ZuulFilter { private static final Logger logger = LoggerFactory.getLogger(PreRequestLogFilter.class); private final RateLimiter rateLimiter = RateLimiter.create(1000.0); @Override public Object run() { try { RequestContext currentContext = RequestContext.getCurrentContext(); HttpServletResponse response = currentContext.getResponse(); HttpServletRequest reqeust = currentContext.getRequest(); currentContext.addZuulRequestHeader("userId","123");//向子系統(tǒng)http頭寫數(shù)據(jù) currentContext.addZuulRequestHeader("userName","test"); PreRequestLogFilter.logger.info( String.format("send %s request to %s", reqeust.getMethod(), reqeust.getRequestURL().toString())); if (!rateLimiter.tryAcquire()) { HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS; response.setContentType(MediaType.TEXT_PLAIN_VALUE); response.setStatus(httpStatus.value()); response.getWriter().append(httpStatus.getReasonPhrase()); currentContext.setSendZuulResponse(false); throw new ZuulException( httpStatus.getReasonPhrase(), httpStatus.value(), httpStatus.getReasonPhrase() ); } } catch (java.lang.Exception e) { ReflectionUtils.rethrowRuntimeException(e); } return null; } @Override public boolean shouldFilter() { // 判斷是否需要過濾 return true; } @Override public String filterType() { return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { return Ordered.HIGHEST_PRECEDENCE; } }
在主程中注入這個過濾器
@Bean public PreRequestLogFilter preRequestLogFilter() { return new PreRequestLogFilter(); }
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。