新建config工程,導入依賴,config工程需要作為一個服務注冊到eureka上,這里我使用了父工程統一管理依賴,就不用聲名版本了
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
啟動類添加注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
config工程的配置文件
spring: application: name: config-server cloud: config: server: git: uri: https://gitee.com/liuyifengmvc/cloud-config username: 用戶名 password: 密碼 basedir: 這里可以不用填寫(有默認值),填寫了的話碼雲的的配置文件會被拉取到你指定的目錄下 eureka: client: service-url: defaultZone: http://localhost:8761/eureka/
新建一個工程,導入依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
其他工程直接通過config這個服務拉取配置文件,這個配置文件的spring.application.name+profile拼接起來的名字就是你要拉取的具體的配置文件名,這里拉取的就是order-dev.yml
spring: application: name: order cloud: config: discovery: service-id: CONFIG-SERVER enabled: true enabled: true //這里默認為true可以不用配置 profile: dev
還有就是客戶端的配置文件名盡量使用bootstrap.yml命名,這個是最先加載的配置文件,避免遇到一些啟動時的錯誤
比如當該客戶端涉及到對數據訪問層的操作,
應用啟動時會自動加載數據庫的一些配置,
這時你的配置文件需要從碼雲拉取,
這時就會出現錯誤,所以需要使用bootstrap.yml來管理配置文件拉取
另外我自己也采坑了就是
我是用application.yml配置去eureka拉取config-server獲取配置文件出現的問題
c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
Connect Timeout Exception on Url - http://localhost:8888. Will be trying the next url if available
Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/product/dev":
Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
我的config-server地址是在8080端口他卻去8888端口找,8888端口時是當客戶端連接不上eureka時默認找的端口
於是我把application.yml改名為bootstrap.yml,結果就成功了,這應該就是配置文件加載的順序的原因吧