Spring Cloud Gateway注冊到服務器中心(Consul)


Spring Cloud Gateway注冊到服務器中心(Consul)

准備環境

啟動Consul(./consul agent -dev)作為服務中心,默認是8500端口,然后啟動spring-cloud-provider(9001端口)和spring-cloud-provider-second(9002端口)兩個項目作為微服務。
在Consul管理后台可以看見兩個服務啟動:
Alt text

添加Spring Cloud Gateway項目的依賴項

POM內增加如下依賴:

                <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-consul-discovery</artifactId>
		</dependency>

修改Spring Cloud Gateway項目配置

server:
 port: 9000
spring:
  cloud:
    consul:
      host: 127.0.0.1
      port: 8500
      discovery:
        register: true
    gateway:
      routes:
        - id: test_route
          uri: lb://service-provider
          predicates:
            - Path=/service-provider/{segment}
          filters:
            - SetPath=/{segment}
  application:
    name: PC-ApiGateWay
  • host:Consul的IP地址
  • port:Consul的端口號
  • register:是否將自己注冊到Consul中
  • lb://service-provider:Consul的服務名稱,以{lb://服務名}進行訪問
  • Path:路由要匹配的路徑格式
  • SetPath:設置路徑過濾器,作用是匹配后可以根據分割符進行訪問路徑的設置
  • name:自己注冊到Consul中的名稱

啟動Spring Cloud Gateway項目

啟動后Consul后台可以看見Spring Cloud Gateway項目的注冊內容
Alt text

測試訪問

訪問 “127.0.0.1:9000/service-provider/hello?name=sws” 這個地址,並刷新頁面測試網關的負載均衡。
Alt text
Alt text

可以看出網關代理了后台微服務的功能,並起到了輪詢訪問的作用。

源碼

Github倉庫:https://github.com/sunweisheng/spring-cloud-example


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM