溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在springboot中使用zuul實(shí)現(xiàn)網(wǎng)關(guān)

發(fā)布時(shí)間:2021-05-27 17:27:06 來(lái)源:億速云 閱讀:220 作者:Leah 欄目:編程語(yǔ)言

如何在springboot中使用zuul實(shí)現(xiàn)網(wǎng)關(guān)?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

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開(kāi)頭的路徑被重定向到lind服務(wù)
    serviceId: lind
 add-host-header: true #顯示真實(shí)的http頭
 retryable: false #關(guān)閉Hystrix的重試功能
 ratelimit:
  enabled: true
  # repository: REDIS
  behind-proxy: true
  policies:
    users:
     limit: 5 #限流,每分鐘請(qǐng)求5次
     refresh-interval: 60
     type:
      - user
      - origin
      - url
     #    url類型的限流就是通過(guò)請(qǐng)求路徑區(qū)分
     #    origin是通過(guò)客戶端IP地址區(qū)分
     #    user是通過(guò)授權(quán)用戶進(jìn)行區(qū)分,也包括匿名用戶

3 添加實(shí)現(xiàn)代碼

http攔截器,獲取用戶ID,為子服務(wù)進(jìn)行傳遞

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頭寫(xiě)數(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() {
  // 判斷是否需要過(guò)濾
  return true;
 }
 @Override
 public String filterType() {
  return FilterConstants.PRE_TYPE;
 }
 @Override
 public int filterOrder() {
  return Ordered.HIGHEST_PRECEDENCE;
 }
}

在主程中注入這個(gè)過(guò)濾器

@Bean
 public PreRequestLogFilter preRequestLogFilter() {
  return new PreRequestLogFilter();
 }

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI