繼續前面搭建的spring cloud。
這里是基於rabbitMQ搭建的,首先需要在電腦上安裝rabbitMQ。
在client端和server端分別加上如下依賴
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-bus-amqp', version: '1.0.1.RELEASE'
AMQP (Advanced Message Queuing Protocol)是一種通訊協議,而rabbitMQ就是使用的這種通訊協議。
client端的application.properties加上如下
spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=root spring.rabbitmq.password=root
client端的configuration包下的配置類文件上應該有@ConfigurationProperties()注解
@Data @Component @ConfigurationProperties(prefix = "fzk") public class BaseConfiguration { private String nick; }
在每個注入了這個configuration的類加上@FreshScope注解
@RestController @RefreshScopepublic class ClientApplication { @Autowired Base base; @RequestMapping(value = "/foo", method = RequestMethod.GET) public String foo() { return base.getNick(); } }
完成之后執行下面命令下載jar包。
gradle build
gradle eclipse
server端同樣編譯后,先啟動server端,在啟動client端。
瀏覽器上輸入localhost:8889/foo會看到獲取到的數據。去gitlab修改下fzk-beta.properties,重新在瀏覽器上輸入,發現現在獲取的還是原來的數據,並沒有修改。從服務端(http://localhost:8888/fzk/beta)可以獲取到最新的數據。這里想讓client端不重啟服務就能獲取到更新后的數據需要手動發送一個post請求到client端(http://localhost:8889/fresh)
$ curl -X POST http://localhost:8889/refresh
["config.client.version","fzk.nick"]
所以想數的時,這里並不是完全的自動。還需要調用一個接口,這個接口一般是通過存放config的push事件來觸發的,如果一個服務可以直接寫在webhook中。但是如果需要觸發多個服務自動更新,可以在jenkins配置一個job,webhook出去這個job,這個job來觸發多個服務的post請求操作。