Nacos 使用
環境準備
下載 Nacos 并啟動 Nacos server。
啟動配置管理
啟動了 Nacos server 后,您就可以參考以下示例代碼,為您的 Spring Cloud 應用啟動 Nacos 配置管理服務了。完整示例代碼請參考:nacos-spring-cloud-config-example
注意:版本?2.1.x.RELEASE?對應的是 Spring Boot 2.1.x 版本。版本?2.0.x.RELEASE?對應的是 Spring Boot 2.0.x 版本,版本?1.5.x.RELEASE?對應的是 Spring Boot 1.5.x 版本。
更多版本對應關系參考:版本說明 Wiki
說明:之所以需要配置?spring.application.name?,是因為它是構成 Nacos 配置管理?dataId字段的一部分。
在 Nacos Spring Cloud 中,dataId?的完整格式如下:
${prefix}-${spring.profiles.active}.${file-extension}- prefix?默認為?spring.application.name?的值,也可以通過配置項?spring.cloud.nacos.config.prefix來配置。
- spring.profiles.active?即為當前環境對應的 profile,詳情可以參考?Spring Boot文檔。?注意:當?spring.profiles.active?為空時,對應的連接符?-?也將不存在,dataId 的拼接格式變成?${prefix}.${file-extension}
- file-exetension?為配置內容的數據格式,可以通過配置項?spring.cloud.nacos.config.file-extension?來配置。目前只支持?properties?和?yaml?類型。
運行?NacosConfigApplication,調用?curl http://localhost:8080/config/get,返回內容是?true。
再次調用?Nacos Open API?向 Nacos server 發布配置:dataId 為example.properties,內容為useLocalCache=false
啟動服務發現
本節通過實現一個簡單的?echo service?演示如何在您的 Spring Cloud 項目中啟用 Nacos 的服務發現功能,如下圖示:
完整示例代碼請參考:nacos-spring-cloud-discovery-example
注意:版本?2.1.x.RELEASE?對應的是 Spring Boot 2.1.x 版本。版本?2.0.x.RELEASE?對應的是 Spring Boot 2.0.x 版本,版本?1.5.x.RELEASE?對應的是 Spring Boot 1.5.x 版本。
更多版本對應關系參考:版本說明 Wiki
i. 在?application.properties?中配置 Nacos server 的地址:
server.port=8070 spring.application.name=service-providerspring.cloud.nacos.discovery.server-addr=127.0.0.1:8848ii. 通過 Spring Cloud 原生注解?@EnableDiscoveryClient?開啟服務注冊發現功能:
@SpringBootApplication @EnableDiscoveryClient public class NacosProviderApplication {public static void main(String[] args) {SpringApplication.run(NacosProviderApplication.class, args);}@RestControllerclass EchoController {@RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)public String echo(@PathVariable String string) {return "Hello Nacos Discovery " + string;}} }i. 在?application.properties?中配置 Nacos server 的地址:
server.port=8080 spring.application.name=service-consumerspring.cloud.nacos.discovery.server-addr=127.0.0.1:8848ii. 通過 Spring Cloud 原生注解?@EnableDiscoveryClient?開啟服務注冊發現功能。給?RestTemplate?實例添加?@LoadBalanced?注解,開啟?@LoadBalanced?與?Ribbon?的集成:
@SpringBootApplication @EnableDiscoveryClient public class NacosConsumerApplication {@LoadBalanced@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(NacosConsumerApplication.class, args);}@RestControllerpublic class TestController {private final RestTemplate restTemplate;@Autowiredpublic TestController(RestTemplate restTemplate) {this.restTemplate = restTemplate;}@RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)public String echo(@PathVariable String str) {return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);}} }總結
- 上一篇: 中芯国际发布重要公告 又一批人才获得3.
- 下一篇: 光学字符识别 Tesseract-OCR