Spring Cloud之搭建動態Zuul網關路由轉發


傳統方式將路由規則配置在配置文件中,如果路由規則發生了改變,需要重啟服務器。這時候我們結合上節課內容整合SpringCloud Config分布式配置中心,實現動態路由規則。

將yml的內容粘貼到碼雲上:

###注冊 中心
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8100/eureka/
server:  ##api網關端口號
  port: 80
###網關名稱
spring:   ##網關服務名稱
  application:
    name: service-zuul
### 配置網關反向代理    
zuul:
  routes:
    api-member:  ##隨便寫的
     ### 以 /api-member/訪問轉發到會員服務   通過別名找
      path: /api-member/**
      serviceId: app-toov5-member  ##別名  如果集群的話  默認整合了ribbon 實現輪訓 負載均衡
    api-order:   ##隨便寫的
        ### 以 /api-order/訪問轉發到訂單服務
      path: /api-order/**
      serviceId: app-toov5-order   ##別名

  

添加到依賴:

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

 可以實現手動刷新 

 

yml中添加:

###默認服務讀取eureka注冊服務列表 默認間隔30秒

###開啟所有監控中心接口
management:
  endpoints:
    web:
      exposure:
        include: "*"

  開啟所有監控中心接口

 

啟動類里面添加:

 //zuul配置使用config實現實時更新 
   @RefreshScope
   @ConfigurationProperties("zuul")
   public ZuulProperties zuulProperties() {
       return new ZuulProperties();
   }

 

 

package com.toov5;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy  //開啟網關代理
public class AppGateway {
   public static void main(String[] args) {
   SpringApplication.run(AppGateway.class, args);     
}
   //zuul配置使用config實現實時更新 
   @RefreshScope
   @ConfigurationProperties("zuul")
   public ZuulProperties zuulProperties() {
       return new ZuulProperties();
   }
   
   
}

yml

###注冊 中心
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8100/eureka/
server:  ##api網關端口號
  port: 80
###網關名稱
spring:   ##網關服務名稱
  application:
    name: service-zuul
  ###網關名稱  
  cloud:
    config:
    ####讀取后綴
      profile: dev
      ####讀取config-server注冊地址
      discovery:
        service-id: confi
    
### 配置網關反向代理    
#zuul:
#  routes:
#    api-member:  ##隨便寫的
#     ### 以 /api-member/訪問轉發到會員服務   通過別名找
#      path: /api-member/**
#      serviceId: app-toov5-member  ##別名  如果集群的話  默認整合了ribbon 實現輪訓 負載均衡
#    api-order:   ##隨便寫的
#        ### 以 /api-order/訪問轉發到訂單服務
#      path: /api-order/**
#      serviceId: app-toov5-order   ##別名

  

 啟動eureka和configserver

 

訪問: 

 可以讀取到

 

 

啟動 gateway

然后啟動 member 

 訪問:

 

配置文件是從git讀取的,成功!

 

 發生變更后同樣需要 post刷新下。

 


免責聲明!

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



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