Nacos 入門

簡介

【官方文檔】

  • 前四個(gè)字母為Nameing和Configuration的前兩個(gè)字母,最后的s為Service。Nacos是一個(gè)更易于構(gòu)建原生應(yīng)用的動(dòng)態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺(tái)。

  • 能夠替代Eureka做服務(wù)注冊中心、替代Config做服務(wù)配置中心

  • Nacos支持AP、CP的切換

Docker安裝單機(jī)版Nacos

  • 進(jìn)入一個(gè)文件夾,然后Clone項(xiàng)目
git clone https://github.com/nacos-group/nacos-docker.git
cd nacos-docker
  • 使用MySQL5.7
docker-compose -f example/standalone-mysql-5.7.yaml up
  • 使用MySQL8
docker-compose -f example/standalone-mysql-8.yaml up

Nacos 作為服務(wù)注冊中心

服務(wù)提供者

新建module
pom.xml的依賴
<dependencies>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- SpringBoot整合Web組件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>
application.yml
server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.138.135:8848 # 配置Nacos地址

management:
  endpoints:
    web:
      exposure:
        include: '*'
啟動(dòng)類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentApplication9001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentApplication9001.class,args);
    }
}
一個(gè)簡單的測試controller
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/payment/nacos")
    public String getPayment() {

        String result = "nacos registry, serverPort: " + serverPort;

        return result;
    }
}

參考上面步驟,再新建一個(gè)提供者實(shí)例,端口9002,或者使用idea啟動(dòng)多實(shí)例,用于下面演示負(fù)載均衡

服務(wù)消費(fèi)者

新建module
pom.xml的依賴
<dependencies>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- SpringBoot整合Web組件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>
application.yml
server:
  port: 8400

spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.138.135:8848 # 配置Nacos地址


# 消費(fèi)者將要去訪問的微服務(wù)名稱(注冊成功進(jìn)nacos的微服務(wù)提供者)
service-url:
  nacos-user-service: http://nacos-payment-provider
啟動(dòng)類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class OrderApplication8400 {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication8400.class, args);
    }

}
RestTemplate配置類
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}
一個(gè)簡單的測試controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serverUrl;

    @GetMapping("/consumer/payment/nacos")
    public String getPayment() {
        String url = serverUrl + "/payment/nacos";
        return restTemplate.getForObject(url, String.class);
    }
}

測試

啟動(dòng)2個(gè)提供者和1個(gè)消費(fèi)者服務(wù)

瀏覽器反復(fù)訪問 http://localhost:8400/consumer/payment/nacos 可以看到會(huì)輪詢請求提供者服務(wù)的不同實(shí)例

之所以可以實(shí)現(xiàn)負(fù)載均衡,是因?yàn)閚acos的依賴默認(rèn)引入了ribbon

Nacos作為配置中心

新建module
pom.xml
<dependencies>
        <!--nacos-config-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <!--nacos-discovery-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--web + actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  </dependencies>
bootstrap.yml
server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.138.135:8848 # Nacos服務(wù)注冊中心地址
      config:
        server-addr: 192.168.138.135:8848 #Nacos作為配置中心地址
        file-extension: yaml #指定yaml格式的配置
#        group: DEFAULT_GROUP
#        namespace: eeba7661-6b5e-46c6-aa45-5df57f48091f


# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml

# nacos-config-client-test.yaml   ----> config.info
application.yml
spring:
  profiles:
    active: dev # 表示開發(fā)環(huán)境
    #active: test # 表示測試環(huán)境
啟動(dòng)類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ConfigApplication3377 {

    public static void main(String[] args) {
        SpringApplication.run(ConfigApplication3377.class, args);
    }

}
測試controller
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope // 支持Nacos的動(dòng)態(tài)刷新功能
public class TestController {

    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/config/info")
    public String getConfigInfo() {
        return configInfo;
    }
}

Naocs的配置文件的dataId命名規(guī)則:${prefix}-${spring.profile.active}.${file-extension}

如:nacos-config-client-dev.yaml

這里的后綴應(yīng)該是yaml而不是yml

  • prefix 默認(rèn)為 spring.application.name 的值,也可以通過配置項(xiàng) spring.cloud.nacos.config.prefix來配置。
  • spring.profiles.active 即為當(dāng)前環(huán)境對應(yīng)的 profile,詳情可以參考 Spring Boot文檔注意:當(dāng) spring.profiles.active 為空時(shí),對應(yīng)的連接符 - 也將不存在,dataId 的拼接格式變成 ${prefix}.${file-extension}
  • file-exetension 為配置內(nèi)容的數(shù)據(jù)格式,可以通過配置項(xiàng) spring.cloud.nacos.config.file-extension 來配置。目前只支持 propertiesyaml 類型

在控制面板中配置一個(gè)yaml文件,用于測試

配置內(nèi)容如下:

然后啟動(dòng)該服務(wù),就會(huì)自動(dòng)去讀取 nacos-config-client-dev.yaml的配置內(nèi)容

訪問:http://localhost:3377/config/info 可以看到配置信息

接著,在Nacos控制面板編輯配置內(nèi)容,將version=1改為version=2

再訪問http://localhost:3377/config/info 可以看到信息發(fā)生了改變,實(shí)現(xiàn)了自動(dòng)刷新功能

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Nacos 是什么? https://nacos.io/zh-cn/docs/what-is-nacos.html...
    大雪冬至?xí)r閱讀 3,622評論 0 0
  • 文章首發(fā)于微信公眾號《程序員果果》地址:https://mp.weixin.qq.com/s/H-rFegXVo_...
    程序員果果閱讀 1,714評論 0 38
  • 最近在做微服務(wù)項(xiàng)目中公司開始使用Nacos,所以決定今天簡單的學(xué)習(xí)入門。Nacos致力于是微服務(wù)注冊、發(fā)現(xiàn)和配置。...
    非典型_程序員閱讀 4,350評論 4 7
  • 久違的晴天,家長會(huì)。 家長大會(huì)開好到教室時(shí),離放學(xué)已經(jīng)沒多少時(shí)間了。班主任說已經(jīng)安排了三個(gè)家長分享經(jīng)驗(yàn)。 放學(xué)鈴聲...
    飄雪兒5閱讀 7,818評論 16 22
  • 今天感恩節(jié)哎,感謝一直在我身邊的親朋好友。感恩相遇!感恩不離不棄。 中午開了第一次的黨會(huì),身份的轉(zhuǎn)變要...
    余生動(dòng)聽閱讀 10,834評論 0 11

友情鏈接更多精彩內(nèi)容