Back to Javatutorial

SpringCloudAlibabaNacos

docs/Spring全家桶/SpringCloudAlibaba/SpringCloudAlibabaNacos.md

1.0.039.1 KB
Original Source

Nacos ӢȫΪ Dynamic Naming and Configuration ServiceһɰͰŶʹ Java ԿĿԴĿ

Nacos һڰԭӦõĶ̬֡úͷƽ̨ο Nacos

Nacos 3 ɣ

ɲȫ
Nanaming/nameServerעģ Spring Cloud Eureka Ĺơ
coconfigurationģ Spring Cloud Config+Spring Cloud Bus Ĺơ
sservice񣬱ʾ Nacos ʵֵķעĺĶԷΪĵġ

ǿԽ Nacos ɷעĺĵ壬滻 Eureka Ϊעģʵַע뷢֣滻 Spring Cloud Config ΪģʵõĶ̬ˢ¡

Nacos Ϊעľʮꡰ˫ʮһĺ忼飬мáȶɿ׿Խŵ㣬԰ûݡ׵ع͹΢Ӧá

Nacos ּ֧͡񡱵ķ֡ú͹

Nacos

Nacos ṩһϵмõԣܹǿٵʵֶ̬֡õȹܡ

Nacos ֻ֧ DNS RPC ķ֡ṩʹԭ SDKOpenAPI һ Agent TODO Nacos ע󣬷߿ Nacos ͨ DNS TODO HTTP&API ҡַ

񽡿

Nacos ṩԷʵʱ飬ֹܹ͵ʵϡNacos ṩһDẒܹǸݽ״̬ĿԼ

̬÷

̬÷ĻⲿͶ̬ķʽлӦúͷá

̬ñʱ²ӦúͷҪùøӸЧݡ

Ļʵ״̬ø򵥣÷赯չøס

Nacos ṩһõ UI ǹзӦõáNacos ṩð汾١˿ȸһعԼͻø״̬ڵһϵп伴õùԣǸȫйñͽñķա

̬ DNS

Nacos ṩ˶̬ DNS ܹǸ׵ʵָؾ⡢Լļ DNS

Nacos ṩһЩ򵥵 DNS APIs TODO԰ǹĹͿõ IP:PORT б

Ԫݹ

Nacos Ǵ΢ƽ̨ӽǹĵзԪݣڡľ̬Ľ״̬·ɼȫԡ SLA Լ metrics ͳݡ

Nacos

Eureka ƣNacos Ҳ CSClient/Serverͻ/ܹ±

Nacos ServerNacos ˣ Eureka Server ͬNacos Server ɰͰŶʹ Java Աд Nacos Server صַûûֻҪֱزмɡNacos Server Ϊעģ Nacos Client ʵַע뷢֡
Nacos Server Ϊģ Nacos Client ڲ£ʵõĶ̬ˢ¡
Nacos ClientNacos ͻˣָͨ΢ܹеĸûԼʹöԱдNacos Client ͨ spring-cloud-starter-alibaba-nacos-discoveryڷעģNacos Serverʵַע뷢֡
Nacos Client ͨ spring-cloud-starter-alibaba-nacos-configģNacos ServerʵõĶ̬ˢ¡

Nacos ע

Nacos ΪעĿʵַע뷢֣ͼ

ͼ1Nacos ע뷢

ͼ 1 й漰 3 ɫ

  • עģRegister Serviceһ Nacos ServerΪṩߺͷṩעͷֹܡ
  • ṩߣProvider Serviceһ Nacos ClientڶԼṩķעᵽעģԹ߷ֺ͵á
  • ߣConsumer Serviceһ Nacos ClientѷԴӷעĻȡбķ

Nacos ʵַע뷢ֵ£

  1. Nacos ٷṩҳУ Nacos Server С
  2. ṩ Nacos Client ʱѷԷspring.application.nameķʽעᵽעģNacos Server
  3. Nacos Client ʱҲὫԼķעᵽעģ
  4. עͬʱӷעĻȡһݷעбϢбаעᵽעϵķϢṩߺϢ
  5. ڻȡ˷ṩߵϢ󣬷ͨ HTTP ϢмԶ̵÷ṩṩķ

װ Nacos Server

Nacos 2.0.3 Ϊʾΰװ Nacos Server¡

1. ʹ Nacos Server ҳҳ· nacos-server-2.0.3.zipͼ

ͼ2Nacos Server

2. ɺ󣬽ѹ nacos-server-2.0.3.zipĿ¼ṹ¡

ͼ3Nacos Server Ŀ¼ṹ

Nacos Server ¸Ŀ¼˵£

  • binڴ Nacos Ŀִ
  • confڴ Nacos ļ
  • targetڴ Nacos Ӧõ jar

3. дڣת Nacos Server װĿ¼ bin £ִԵģʽ Nacos Server

startup.cmd -m standalone

4. Nacos Server ־¡

"nacos is starting with standalone"

     ,--.
   ,--.'|

,--,: : | Nacos 2.0.3 ,--.'| ' : ,---. Running in stand alone mode, All function modules | : : | | ' ,'\ .--.--. Port: 8848 : | \ | : ,--.--. ,---. / / | / / ' Pid: 27512 | : ' '; | / \ / . ; ,. :| : /./ Console: http://192.168.3.138:8848/nacos/index.html ' ' ;. ;.--. .-. | / / '' | |: :| : ;_ | | | \ | \__\/: . .. ' / ' | .; : \ \ . https://nacos.io ' : | ; .' ," .--.; |' ; :__| : | ----. \ | | '--' / / ,. |' | '.'|\ \ / / /--' / ' : | ; : .' \ : : ----' '--'. / ; |.' | , .-./\ \ / --'---' '---' -----' ----'

2021-11-08 16:16:38,877 INFO Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@5ab9b447' of type [org.springframework.security.access.expression.method
.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-11-08 16:16:38,884 INFO Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by al
l BeanPostProcessors (for example: not eligible for auto-proxying)
2021-11-08 16:16:40,001 INFO Tomcat initialized with port(s): 8848 (http)
2021-11-08 16:16:40,713 INFO Root WebApplicationContext: initialization completed in 14868 ms
2021-11-08 16:16:52,351 INFO Initializing ExecutorService 'applicationTaskExecutor'
2021-11-08 16:16:52,560 INFO Adding welcome page: class path resource [static/index.html]
2021-11-08 16:16:54,239 INFO Creating filter chain: Ant [pattern='/**'], []
2021-11-08 16:16:54,344 INFO Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@7dd611c8, org.springframework.security.web.con
text.SecurityContextPersistenceFilter@5c7668ba, org.springframework.security.web.header.HeaderWriterFilter@fb713e7, org.springframework.security.web.csrf.CsrfFilter@6ec7bce0, org.springframework.secur
ity.web.authentication.logout.LogoutFilter@7d9ba6c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@158f4cfe, org.springframework.security.web.servletapi.SecurityContextHolderAwa
reRequestFilter@6c6333cd, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5d425813, org.springframework.security.web.session.SessionManagementFilter@13741d5a, org.springf
ramework.security.web.access.ExceptionTranslationFilter@3727f0ee]
2021-11-08 16:16:54,948 INFO Initializing ExecutorService 'taskScheduler'
2021-11-08 16:16:54,977 INFO Exposing 16 endpoint(s) beneath base path '/actuator'
2021-11-08 16:16:55,309 INFO Tomcat started on port(s): 8848 (http) with context path '/nacos'
2021-11-08 16:16:55,319 INFO Nacos started successfully in stand alone mode. use embedded storage

5. ʹʡhttp://localhost:8848/nacosת Nacos Server ½ҳ棬ͼ

ͼ4Nacos Server ½ҳ

6. ڵ½ҳ¼루Ĭ϶ nacosύťת Nacos Server ̨ҳͼ

ͼ5Nacos Server ̨

ԴˣǾ Nacos Server ءװй

ṩ

һṩߣ¡

  1. һΪ spring-cloud-alibaba-demo Maven ù̵ 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        spring-boot-starter-parent
        <version>2.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>net.biancheng.c</groupId>
    spring-cloud-alibaba-demo
    <version>1.0-SNAPSHOT</version>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.16.18</lombok.version>
        <spring-cloud.version>2020.0.4</spring-cloud.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <!--Spring Cloud Alibaba İ汾Ϣ-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                spring-cloud-alibaba-dependencies
                <version>2021.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--Spring Cloud İ汾Ϣ-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                spring-cloud-dependencies
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

ڸù̵ pom.xml Уͨ dependencyManagement Spring Cloud Alibaba İ汾Ϣйùµĸģ Spring Cloud Alibaba ĸʱͲҪָ汾ˡ

2. spring-cloud-alibaba-demo £һΪ spring-cloud-alibaba-provider-8001 Spring Boot ģ飬 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>net.biancheng.c</groupId>
        <version>1.0-SNAPSHOT</version>
        spring-cloud-alibaba-demo
    </parent>


    <groupId>net.biancheng.c</groupId>
    spring-cloud-alibaba-provider-8001
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cloud-alibaba-provider-8001</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-starter-web
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-devtools
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            lombok
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-starter-test
            <scope>test</scope>
        </dependency>
        <!--Spring Cloud Alibaba Nacos discovery -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            spring-cloud-starter-alibaba-nacos-discovery
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                spring-boot-maven-plugin
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            lombok
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3. spring-cloud-alibaba-provider-8001 ļ application.properties ã¡

#˿ں
server.port=8001
#
spring.application.name=spring-cloud-alibaba-provider
#Nacos Server ĵַ
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
management.endpoints.web.exposure.include=*

4. net.biacheng.c.controller £һΪ DeptController Controller ࣬¡

package net.biancheng.c.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class DeptController {
    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/dept/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id) {
        return "<h2>cʳɹ</h2>spring-cloud-alibaba-provider
 ˿ںţ " + serverPort + "
 IJ" + id;
    }

}

5. spring-cloud-alibaba-provider-8001 ϣʹ @EnableDiscoveryClient ע⿪ Nacos ֹܣ¡

package net.biancheng.c;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient //ֹ
public class SpringCloudAlibabaProvider8001Application {

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

}

6. spring-cloud-alibaba-provider-8001ʹʡhttp://localhost:8001/dept/nacos/1ͼ

ͼ6ṩ

7. ʹʡhttp://localhost:8848/nacos鿴µġбͼ

ͼ7עб

ͼ 7 ԿǴķṩ spring-cloud-alibaba-provider-8001 ṩķѾעᵽ Nacos Server ˡ

棬Ǿһ spring-cloud-alibaba-provider-8001 ṩķ񣬲¡

1. spring-cloud-alibaba-demo £һΪ spring-cloud-alibaba-consumer-nacos-8801 Spring Boot ģ飬 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>net.biancheng.c</groupId>
        <version>1.0-SNAPSHOT</version>
        spring-cloud-alibaba-demo
    </parent>
    <groupId>net.biancheng.c</groupId>
    spring-cloud-alibaba-consumer-nacos-8081
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cloud-alibaba-consumer-nacos-8081</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--SpringCloud ailibaba nacos discovery-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            spring-cloud-starter-alibaba-nacos-discovery
        </dependency>
        <!-- Netflix Ribbon ͣά׶Σ°汾 Nacos discovery ѾƳ Ribbon ʱҪ loadbalancer  -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            spring-cloud-loadbalancer
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-starter-web
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-devtools
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            lombok
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-starter-test
            <scope>test</scope>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                spring-boot-maven-plugin
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            lombok
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

ע⣺ Netflix Ribbon Ѿͣά״̬Nacos Discovery Ѿͣ˶ Ribbon ֧֣Ҫڷߵ pom.xml spring-cloud-loadbalancer ܵ÷ṩṩķ

2. spring-cloud-alibaba-consumer-nacos-8801 ļ application.yml Уá



server:
  port: 8801  #˿ں
spring:
  application:
    name: spring-cloud-alibaba-consumer #
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848  #Nacos server ĵַ

#ϢĬãԶãĿDz Controller Ӳṩߵķ

service-url:
  nacos-user-service: http://spring-cloud-alibaba-provider #ṩߵķ

3. spring-cloud-alibaba-consumer-nacos-8801 ϣʹ @EnableDiscoveryClient ע⿪ֹܣ¡

package net.biancheng.c;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient // ע뷢ֹ
public class SpringCloudAlibabaConsumerNacos8801Application {

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

}

4. net.biancheng.c.config ´һΪ ApplicationContextBean ࣬ʹ @LoadBalanced ע Ribbon мɿؾ⹦ܣ¡

package net.biancheng.c.config;


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 ApplicationContextBean {

    @Bean
    @LoadBalanced // Ribbon ɣؾ⹦
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

}

5. net.biancheng.c.controller £һΪ DeptController_Consumer Controller ࣬¡

package net.biancheng.c.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class DeptController_Consumer {

    @Resource
    private RestTemplate restTemplate;
    
    @Value("${service-url.nacos-user-service}")
    private String serverURL; //ṩߵķ
    
    @GetMapping("/consumer/dept/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Long id) {
        return restTemplate.getForObject(serverURL + "/dept/nacos/" + id, String.class);
    }

}

6. spring-cloud-alibaba-consumer-nacos-8801鿴 Nacos Server ķбͼ

ͼ8

7. ʹʡhttp://localhost:8801/consumer/dept/nacos/1ͼ

ͼ9ߵ÷

Nacos

Nacos Server Ϊģ Spring Cloud ӦõⲿýͳһؼлֻҪӦõ POM ļ spring-cloud-starter-alibaba-nacos-config ʵõĻȡ붯̬ˢ¡

ùĽǶȿNacos ˵ Spring Cloud Config Ⱥ Nacos ʹø򵥣Ҳ١

ͨһʵʾ Nacos ʵõͳһͶ̬ˢµġ

1. spring-cloud-alibaba-demo £һΪ spring-cloud-alibaba-config-client-3377 Spring Boot ģ飬 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>net.biancheng.c</groupId>
        <version>1.0-SNAPSHOT</version>
        spring-cloud-alibaba-demo
    </parent>
    <groupId>net.biancheng.c</groupId>
    spring-cloud-alibaba-config-client-3377
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cloud-alibaba-nacos-config-client-3377</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-starter-web
        </dependency>
        <!--SpringCloud2020Ժİ汾Ĭϲ bootstrap ãҪpomʽ룺-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            spring-cloud-starter-bootstrap
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-devtools
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            lombok
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-starter-test
            <scope>test</scope>
        </dependency>
        <!--Spring Cloud Alibaba Config -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            spring-cloud-starter-alibaba-nacos-config
        </dependency>
        <!--SpringCloud ailibaba nacos ע뷢ģ -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            spring-cloud-starter-alibaba-nacos-discovery
        </dependency>
        <!--Spring Boot ģ-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            spring-boot-starter-actuator
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                spring-boot-maven-plugin
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            lombok
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

ע⣺ʹõ Spring Cloud 2020 汾Ĭϲ bootstrapҪӦʱ bootstrap ã bootstrap.yml bootstrap.propertiesҪ pom.xml ʽ spring-cloud-starter-bootstrap

2. spring-cloud-alibaba-config-client-3377 · /resources Ŀ¼£һ bootstrap.yml¡

server:
  port: 3377 #˿ں
spring:
  application:
    name: config-client #
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848 #Nacosעĵַ


      config:
        server-addr: 127.0.0.1:8848 #NacosΪĵַ
        file-extension: yaml #ָyamlʽ

3. spring-cloud-alibaba-config-client-3377 · /resources Ŀ¼£һ application.yml¡

spring:
  profiles:
    active: dev # dev 

4. net.biancheng.c.controller £һΪ ConfigClientController Controller ࣬ڸʹ @RefreshScope עʵõԶ£¡

package net.biancheng.c.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
public class ConfigClientController {

    @Value("${config.info}")
    private String ConfigInfo;
    
    @GetMapping("/config/info")
    public String getConfigInfo(){
        return ConfigInfo;
    }

}

5. spring-cloud-alibaba-config-client-3377 ϣʹ @EnableDiscoveryClient ע⿪ֹܣ¡

package net.biancheng.c;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudAlibabaNacosConfigClient3377Application {

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

}

6. Nacos Server Nacos Server ̨ġùµġбУ+ť½á

Data ID:        config-client-dev.yaml


Group  :        DEFAULT_GROUP

øʽ:        YAML

:      config:
                  info: c.biancheng.net

Nacos Server Уõ dataId Data IDʽ£

${prefix}-${spring.profiles.active}.${file-extension}

dataId ʽи˵£

  • ${prefix}ĬȡֵΪ΢ķļ spring.application.name ֵǿļͨ spring.cloud.nacos.config.prefix ָ
  • ${spring.profiles.active}ʾǰӦ Profile devtestprod ȡûָ Profile ʱӦӷҲڣ dataId ĸʽ ${prefix}.${file-extension}
  • ${file-extension}ʾݵݸʽǿļͨ spring.cloud.nacos.config.file-extension ã properties yaml

7. spring-cloud-alibaba-config-client-3377ʹʡhttp://localhost:3377/config/infoͼ

ͼ10Nacos Config

8. Nacos Server У config-client-dev.yaml е޸ijݡ

config:
    info: this is c.biancheng.net

9. ڲ spring-cloud-alibaba-config-client-3377 £ʹٴηʡhttp://localhost:3377/config/infoͼ

ͼ11Nacos Cofig

Nacos Server Ⱥ

ʵʵĿУһ΢ϵͳʮʮٸ΢ɡ Щȫעᵽͬһ̨ Nacos Serverͼпܵ Nacos Server Ϊظյ΢ϵͳֱ̱ӵİ취ʹ Nacos Server Ⱥ

Nacos Server ļȺһʮԵŵ㣬ǾǿԱϵͳĸ߿ԡڼȺУֻҪе Nacos Server ֹͣNacos Client ͻԴӼȺ Nacos Server ϻȡϢãᵼϵͳ̱ Nacos Server Ⱥĸ߿ԡ

ͼչʾ Nacos Server ȺĻܹ

ͼ12Nacos Server Ⱥܹ

Windows ϵͳΪʾβ Nacos Server Ⱥ

1. MySQL У½һΪ nacos_config ݿʵڸݿִ SQL 䡣

/******************************************/
/*   ݿȫ = nacos_config   */
/*    = config_info   */
/******************************************/
CREATE TABLE `config_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) DEFAULT NULL,
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'ʱ',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '޸ʱ',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '⻧ֶ',
  `c_desc` varchar(256) DEFAULT NULL,
  `c_use` varchar(64) DEFAULT NULL,
  `effect` varchar(64) DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL,
  `c_schema` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';


/******************************************/
/*   ݿȫ = nacos_config   */
/*    = config_info_aggr   */
/******************************************/
CREATE TABLE `config_info_aggr` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) NOT NULL COMMENT 'group_id',
  `datum_id` varchar(255) NOT NULL COMMENT 'datum_id',
  `content` longtext NOT NULL COMMENT '',
  `gmt_modified` datetime NOT NULL COMMENT '޸ʱ',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '⻧ֶ',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='⻧ֶ';

/******************************************/
/*   ݿȫ = nacos_config   */
/*    = config_info_beta   */
/******************************************/
CREATE TABLE `config_info_beta` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `beta_ips` varchar(1024) DEFAULT NULL COMMENT 'betaIps',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'ʱ',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '޸ʱ',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `tenant_id` varchar(128) DEFAULT '' COMMENT '⻧ֶ',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';

/******************************************/
/*   ݿȫ = nacos_config   */
/*    = config_info_tag   */
/******************************************/
CREATE TABLE `config_info_tag` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `tag_id` varchar(128) NOT NULL COMMENT 'tag_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'ʱ',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '޸ʱ',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';

/******************************************/
/*   ݿȫ = nacos_config   */
/*    = config_tags_relation   */
/******************************************/
CREATE TABLE `config_tags_relation` (
  `id` bigint(20) NOT NULL COMMENT 'id',
  `tag_name` varchar(128) NOT NULL COMMENT 'tag_name',
  `tag_type` varchar(64) DEFAULT NULL COMMENT 'tag_type',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `nid` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`nid`),
  UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';

/******************************************/
/*   ݿȫ = nacos_config   */
/*    = group_capacity   */
/******************************************/
CREATE TABLE `group_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `group_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Group IDַʾȺ',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '0ʾʹĬֵ',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ʹ',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ôСޣλΪֽڣ0ʾʹĬֵ',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ۺ0ʾʹĬֵ',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ۺݵôСޣλΪֽڣ0ʾʹĬֵ',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ʷ',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'ʱ',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '޸ʱ',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='ȺGroupϢ';

/******************************************/
/*   ݿȫ = nacos_config   */
/*    = his_config_info   */
/******************************************/
CREATE TABLE `his_config_info` (
  `id` bigint(64) unsigned NOT NULL,
  `nid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `data_id` varchar(255) NOT NULL,
  `group_id` varchar(128) NOT NULL,
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL,
  `md5` varchar(32) DEFAULT NULL,
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `src_user` text,
  `src_ip` varchar(50) DEFAULT NULL,
  `op_type` char(10) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '⻧ֶ',
  PRIMARY KEY (`nid`),
  KEY `idx_gmt_create` (`gmt_create`),
  KEY `idx_gmt_modified` (`gmt_modified`),
  KEY `idx_did` (`data_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='⻧';

/******************************************/
/*   ݿȫ = nacos_config   */
/*    = tenant_capacity   */
/******************************************/
CREATE TABLE `tenant_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `tenant_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '0ʾʹĬֵ',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ʹ',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ôСޣλΪֽڣ0ʾʹĬֵ',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ۺ',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ۺݵôСޣλΪֽڣ0ʾʹĬֵ',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'ʷ',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'ʱ',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '޸ʱ',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='⻧Ϣ';

CREATE TABLE `tenant_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `kp` varchar(128) NOT NULL COMMENT 'kp',
  `tenant_id` varchar(128) default '' COMMENT 'tenant_id',
  `tenant_name` varchar(128) default '' COMMENT 'tenant_name',
  `tenant_desc` varchar(256) DEFAULT NULL COMMENT 'tenant_desc',
  `create_source` varchar(32) DEFAULT NULL COMMENT 'create_source',
  `gmt_create` bigint(20) NOT NULL COMMENT 'ʱ',
  `gmt_modified` bigint(20) NOT NULL COMMENT '޸ʱ',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';

CREATE TABLE `users` (
`username` varchar(50) NOT NULL PRIMARY KEY,
`password` varchar(500) NOT NULL,
`enabled` boolean NOT NULL
);

CREATE TABLE `roles` (
`username` varchar(50) NOT NULL,
`role` varchar(50) NOT NULL,
UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE
);

CREATE TABLE `permissions` (
    `role` varchar(50) NOT NULL,
    `resource` varchar(255) NOT NULL,
    `action` varchar(8) NOT NULL,
    UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
);

INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);

INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');

2. Nacos Server װĿ¼µ conf ļУ cluster.conf.example Ϊ cluster.confȻڸļݡ

192.168.3.138:3333
192.168.3.138:4444
192.168.3.138:5555

˵£

  • 192.168.138 Ϊص IP ַòҪд localhost 127.0.0.1 Nacos Server Ⱥܻʧܣ
  • δ Nacos Server ȺĶ˿ڷֱΪ333344445555

3. config Ŀ¼µ application.properties У server.port˿ںţ޸Ϊ 3333ڸļ MySQL ݿã޸¡

server.port=3333
################ MySQL ݿ##################
spring.datasource.platform=mysql


db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
db.user=root
db.password=root

4. Nacos Server Ŀ¼Ƶ̨ϣǵĶ˿ںŷֱ޸Ϊ 4444 5555

5. Nginx޸ Nginx conf Ŀ¼µ nginx.conf ã¡

#user  nobody;
worker_processes  1;


#error_log  logs/error.log;

#error_log  logs/error.log  notice;

#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    upstream cluster{
        server 127.0.0.1:3333;
        server 127.0.0.1:4444;
        server 127.0.0.1:5555;
    }

    server {
        listen       1111;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            #root   html;
            #index  index.html index.htm;
            proxy_pass http://cluster;
        }
    }

}

6. Ⱥе Nacos Serverʱʾ Nacos Server ɹ

"nacos is starting with cluster"


         ,--.
       ,--.'|

   ,--,:  : |                                           Nacos 2.0.3
,`--.'`|  ' :                       ,---.               Running in cluster mode, All function modules
|   :  :  | |                      '   ,'\   .--.--.    Port: ****
:   |   \ | :  ,--.--.     ,---.  /   /   | /  /    '   Pid: 21592
|   : '  '; | /       \   /     \.   ; ,. :|  :  /`./   Console: http://192.168.3.138:3333/nacos/index.html
'   ' ;.    ;.--.  .-. | /    / ''   | |: :|  :  ;_
|   | | \   | \__\/: . ..    ' / '   | .; : \  \    `.      https://nacos.io
'   : |  ; .' ," .--.; |'   ; :__|   :    |  `----.   \
|   | '`--'  /  /  ,.  |'   | '.'|\   \  /  /  /`--'  /
'   : |     ;  :   .'   \   :    : `----'  '--'.     /
;   |.'     |  ,     .-./\   \  /            `--'---'
'---'        `--`---'     `----'

2021-11-09 16:25:00,993 INFO The server IP list of Nacos is [192.168.3.138:3333, 192.168.3.138:4444, 192.168.3.138:5555]

2021-11-09 16:27:07,318 INFO Nacos is starting...

2021-11-09 16:27:08,325 INFO Nacos is starting...

2021-11-09 16:27:09,340 INFO Nacos is starting...

2021-11-09 16:27:10,343 INFO Nacos is starting...

2021-11-09 16:27:10,742 INFO Nacos started successfully in cluster mode. use external storage

7. Ⱥе Nacos Server ɹ˫ Nignx װĿ¼µ nginx.exe Nginx

ͼ13Nginx ű

8. ʹʡhttp://localhost:1111/nacos/ɹ Nacos Server Ŀ̨˵ Nacos Ⱥɹͼ

ͼ14Nacos Ⱥ

9. spring-cloud-alibaba-demo ģļе Nacos Server ַͳһ޸Ϊlocalhost:1111 spring-cloud-alibaba-consumer-nacos-8801 Ϊļ application.yml ¡

server:
  port: 8801  #˿ں
spring:
  application:
    name: spring-cloud-alibaba-consumer #
  cloud:
    nacos:
      discovery:
        #server-addr: localhost:8848  # Nacos Server ĵַ
        server-addr: localhost:1111  #Ⱥ Nacos Server ĵַ

#ϢĬãԶãĿDz Controller Ӳṩߵķ

service-url:
  nacos-user-service: http://spring-cloud-alibaba-provider #ṩߵķ

10. spring-cloud-alibaba-consumer-nacos-8801ʹʡhttp://localhost:1111/nacos鿴µġбͼ

ͼ15עᵽ Nacos Server Ⱥ

ο

https://lijunyi.xyz/docs/SpringCloud/SpringCloud.html#_2-2-x-%E5%88%86%E6%94%AF https://mp.weixin.qq.com/s/2jeovmj77O9Ux96v3A0NtA https://juejin.cn/post/6931922457741770760 https://github.com/D2C-Cai/herring http://c.biancheng.net/springcloud