分散式配置nacos搭建踩坑指南(下)

王三豐發表於2023-02-11

  上一篇介紹了在配置nacos中的碰到的坑,這一篇介紹一下如何正確進行nacos的環境搭建和配置,所以本文分為兩部分,第一部分為環境搭建,介紹如何安裝和執行。第二部分為alibaba Sprint Boot配置,介紹如何正確配置。

  注意:本文基於nacos 2.2.0,alibaba Spring Boot 2.6.11,eclipse,作業系統為windows.

 

                                       一.環境搭建

 

  1.下載nacos

   在github上下載nacos的windows安裝檔案,網址為:https://github.com/alibaba/nacos/releases,這裡選擇2.2.0下載,選擇.zip格式的即可,入下所示:

 

2.執行nacos

  解壓下載回來的zip檔案至D盤,進入bin資料夾,執行:.\startup.cmd -m standalone 啟動nacos,如果看到" Nacos started successfully in stand alone mode. use embedded storage",恭喜!執行成功!如下所示:

 

 

 

3.登入配置介面:

 在瀏覽器中訪問:http://localhost:8848/nacos/,使用者名稱和密碼都是nacos,即可進入後臺配置頁面,如下所示:

 

 

 

 

 第二部分 Spring Boot配置

1.下載alibaba Spring Boot腳手架

  訪問https://start.aliyun.com/bootstrap.html,Group輸入:com.alibaba.cloud,Artifact:nacos-config-sample,元件選擇:Nacos Configuration,Spring Web,Spring Boot Actuator,同時需要引入Spring Cloud下的Cloud Bootstrap。這個在阿里巴巴出版的電子書<<Spring Cloud alibaba 從入門到實戰>>中沒有介紹。如果沒有引入Cloud Bootstrap,在eclipse中執行後必報錯,截圖如下:

  

 

 

 下面是完整的pom.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.11</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>nacos-config-sample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos-config-sample</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud-alibaba.version>2021.0.4.0</spring-cloud-alibaba.version>
        <spring-cloud.version>2021.0.4</spring-cloud.version>
    </properties>

    <dependencies>
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  

2.配置namespace

  訪問http://localhost:8848/nacos/,在後臺新建一個名為testnamespace的namespace,記住它的id:bd1caf11-e4f1-4dd0-9a4b-2c32041c64e2,待會在spring boot配置中要用到,如下所示:

3.配置Properties

在配置管理中,我們選擇剛才新建的testnamespace名稱空間,在這個下面建立配置,新增一個data id為:nacos-config-sample.properties 的配置,配置格式選擇properties.注意,data id的格式為{spring boot 應用名}.properties,兩邊必須要一致,否則報錯!如下所示:

 

4.配置Spring Boot:

1)配置bootstrap.properties

spring.cloud.nacos.config.username=nacos
spring.cloud.nacos.config.password=nacos
spring.cloud.nacos.config.contextPath=/nacos
spring.cloud.nacos.config.server-addr=localhost:8848
spring.cloud.nacos.config.namespace=bd1caf11-e4f1-4dd0-9a4b-2c32041c64e2 
spring.cloud.nacos.config.extension-configs[0].data-id=nacos-config-sample.properties
spring.cloud.nacos.config.extension-configs[0].refresh=true

 

 注意spring.cloud.nacos.config.namespace=bd1caf11-e4f1-4dd0-9a4b-2c32041c64e2,這個namespace就是上面新建名稱空間的id.

 

 2)配置application.properties

spring.application.name=nacos-config-sample
server.port=8080
management.server.port=8081
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

  

3)新建實體類

package com.alibaba.cloud.nacosconfigsample;

import com.alibaba.nacos.api.config.annotation.*;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.*;


@RefreshScope
//@ConfigurationProperties(prefix="user")
public class User {
   
	private String name;
	private int age;
	
	public String getName() {
		return name;
		
	}
	
	public void setName(String name) {
		this.name=name;
		
	}
	
	public int getAge() {
		return this.age;
		
	}
	
	public void setAge(int age) {
		this.age=age;
		
	}
	
}

  

 4)Spring boot啟動類 

package com.alibaba.cloud.nacosconfigsample;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.alibaba.nacos.api.config.annotation.*;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import javax.annotation.*;

@RestController
@SpringBootApplication
@RefreshScope
//@EnableConfigurationProperties(User.class)
public class NacosConfigSampleApplication {

	
	@Value("${user.name}") //import org.springframework.cloud.context.config.annotation.RefreshScope;
	private String userName;
	
	@Value("${user.age}")
	private int age;
	
	@PostConstruct
	public void init() {
		
		System.out.printf("[init] user age is: %s",userName);
	}
	
//	@Autowired
//	private User user;
	
	@RequestMapping("/user")
	public String user() {
		
		return  "user :"+userName;
	//return user.getName();
	}
	
	@PreDestroy
	public void destroy() {
		
		System.out.printf("[destroy] user age : %s ",userName);
	}
	
	
    public static void main(String[] args) {
        SpringApplication.run(NacosConfigSampleApplication.class, args);
    }

}

 

 

5)修改配置中的user.的name,在spring boot中觀察是否更新

 

   

    

相關文章