詳解spring cloud構建微服務架構的網關(API GateWay),springcloud

來源:互聯網
上載者:User

詳解spring cloud構建微服務架構的網關(API GateWay),springcloud

前言

在我們前面的部落格中講到,當服務A需要調用服務B的時候,只需要從Eureka中擷取B服務的註冊執行個體,然後使用Feign來調用B的服務,使用Ribbon來實現負載平衡,但是,當我們同時向用戶端暴漏多個服務的時候,用戶端怎麼調用我們暴漏的服務了,如果我們還想加入安全認證,許可權控制,過濾器以及動態路由等特性了,那麼就需要使用Zuul來實現API GateWay了,下面,我們先來看下Zuul怎麼使用。

一、加入Zuul的依賴

<dependency>       <groupId>org.springframework.cloud</groupId>       <artifactId>spring-cloud-starter-zuul</artifactId>     </dependency>     <dependency>       <groupId>org.springframework.cloud</groupId>       <artifactId>spring-cloud-starter-eureka</artifactId>     </dependency> 

由於,我們需要將Zuul服務註冊到Eureka Server上,同時從Eureka Server上發現註冊的服務,所以這裡我們加上了Eureka的依賴。

二、在應用Application主類上開啟Zuul支援

@SpringBootApplication @EnableZuulProxy // 使用@EnableZuulProxy來開啟Zuul的支援,如果你不想使用Zuul提供的Filter和反向 Proxy的功能的話,此處可以使用@EnableZuulServer註解 public class ZuulApplication {  public static void main(String[] args) {   SpringApplication.run(ZuulApplication.class, args);  } } 

三、在application.yml中增加Zuul的基礎配置資訊

spring:  application:   name: gateway-zuul # 應用程式名稱 server:  port: 8768 #Zuul Server的連接埠號碼 eureka:  client:   service-url:    defaultZone: http://localhost:8761/eureka  instance:   prefer-ip-address: true 

四、在application.yml中增加服務路由配置

前提:在Eureka Server已經註冊了2個服務,分別是:springboot-h2-service和springboot-rest-template-feign,其中springboot-rest-template-feign服務會調用springboot-h2-service服務,springboot-rest-template-feign服務是我們對外提供的服務,也就是說,springboot-rest-template-feign服務是我們暴漏給用戶端調用的。

# 路由配置方式一 #zuul: # routes: #  springboot-rest-template-feign: /templateservice/** #所有請求springboot-rest-template-feign的請求,都會被攔截,並且轉寄到templateservice上   # 路由配置方式二 zuul:  routes:   api-contract: # 其中api-contract是路由名稱,可以隨便定義,但是path和service-id需要一一對應    path: /templateservice/**    service-id: springboot-rest-template-feign # springboot-rest-template-feign為註冊到Eureka上的服務名 ribbon:  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule # 佈建服務端負載平衡策略  

五、驗證

下面我們就可以來進行驗證了,在瀏覽器中輸入:http://localhost:8768/templateservice/template/1就可以看到測試結果了。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.