dubboSpring Cloud

Nacos 的基本应用(Spring Cloud)

2020-10-04  本文已影响0人  吉他手_c156

依赖 maven 坐标

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

application.properties 配置文件

# 应用名称
spring.application.name=spring-alibaba-nacos-demo

# dubbo 协议
dubbo.protocol.id=dubbo
dubbo.protocol.name=dubbo
# dubbo 协议端口( -1 表示自增端口,从 20880 开始)
dubbo.protocol.port=-1
# Dubbo 消费端订阅服务端的应用名,多个服务提供者用逗号分隔
# 这里订阅"自己",会被忽略掉,请根据实际情况添加
dubbo.cloud.subscribed-services=spring-alibaba-nacos-demo

# Nacos帮助文档: https://nacos.io/zh-cn/docs/concepts.html
# Nacos认证信息
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos 服务发现与注册配置,其中子属性 server-addr 指定 Nacos 服务器主机和端口
spring.cloud.nacos.discovery.server-addr=192.168.119.131:8848
# 注册到 nacos 的指定 namespace,默认为 public
spring.cloud.nacos.discovery.namespace=public

nacos 的配置信息一定要放在 bootstrap.properties 文件中

# Nacos帮助文档: https://nacos.io/zh-cn/docs/concepts.html
# Nacos认证信息
spring.cloud.nacos.config.username=nacos
spring.cloud.nacos.config.password=nacos
spring.cloud.nacos.config.contextPath=/nacos
# 设置配置中心服务端地址
spring.cloud.nacos.config.server-addr=192.168.119.131:8848
# Nacos 配置中心的namespace,默认为 public
spring.cloud.nacos.config.namespace=public

简单应用

创建一个 controller 类

@RestController
@RefreshScope   // sppring 的注解,表示当前类中的出行需要动态刷新
public class TestController {

    // :hello word 表示默认值
    @Value("${info:hello word}")
    private String info;

    @GetMapping("/getInfo")
    public String getInfo(){
        return info;
    }
}

在 nacos 中添加配置信息

image.png

重新启动项目访问 getInfo 地址

image.png

可以看到拿到的是配置中心中的地址,如果改变了配置中心的值,不需要重启服务,不需要重新修改配置,返回值也会随之改变

nacos mysql 文件

https://github.com/alibaba/nacos/blob/master/distribution/conf/nacos-mysql.sql

简单的SpringCloud Alibaba, provider ,consmer 搭建

创建聚合项目 spring-cloud-nacos-dubbo-provider

pom 引入依赖

<?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>

    <groupId>org.example</groupId>
    <artifactId>spring-cloud-nacos-dubbo-provider</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>nacos-dubbo-provider-api</module>
        <module>nacos-dubbo-cousumer</module>
        <module>nacos-dubbo-provider</module>
    </modules>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.2.4.RELEASE</spring-boot.version>
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--  nacos config -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

        <!--  nacos 服务注册发现 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!-- dubbo -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-dubbo</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <!-- springCloud -->
            <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>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.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>
                <version>2.3.0.RELEASE</version>
                <configuration>
                    <mainClass>com.example.demo.SpringAlibabaNacosDemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

创建 api 子工程 nacos-dubbo-provider-api

创建公共接口

public interface UserMapper {
    public String getUserName(String userName);
}

创建服务提供方子工程 nacos-dubbo-provider

pom 依赖,引入 nacos,dubbo,springboot,api 子工程依赖

<?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">
    <parent>
        <artifactId>spring-cloud-nacos-dubbo-provider</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>nacos-dubbo-provider</artifactId>

    <dependencies>
        <dependency>
            <artifactId>nacos-dubbo-provider-api</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
        </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>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-dubbo</artifactId>
        </dependency>
    </dependencies>
</project>

实现 api 工程接口

@Service 注解是 dubbo 的注解

@Service
public class UserService implements UserMapper {
    @Override
    public String getUserName(String userName) {
        return userName;
    }
}

启动类

@SpringBootApplication(scanBasePackages = "com.dubbo",
                       scanBasePackageClasses = com.netflix.client.config.DefaultClientConfigImpl.class)
@EnableDiscoveryClient
public class NacosDubboProviderApplication {

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

nacos 的配置要配置在 bootstrap.yml 中

server:
  port: 8081

spring:
  application:
    name: nacos-provider
  cloud:
    nacos:
      config:
        server-addr: 192.168.119.130:8848
      discovery:
        server-addr: 192.168.119.130:8848

dubbo:
  application:
    name: nacos-provider
    #表示采用的dubbo协议
  protocol:
    name: dubbo
    #发布的端口号
    port: 20884
  ##### 调用服务超时时间
  consumer:
    timeout: 5000
  scan:
    base-packages: com.dubbo.service

创建服务消费方子工程 nacos-dubbo-cousumer

pom 依赖,引入 nacos,dubbo,springboot,api 子工程依赖

<?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">
    <parent>
        <artifactId>spring-cloud-nacos-dubbo-provider</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>nacos-dubbo-cousumer</artifactId>

    <dependencies>

        <!--  api公共模块 -->
        <dependency>
            <artifactId>nacos-dubbo-provider-api</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
        </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>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-dubbo</artifactId>
        </dependency>
    </dependencies>
</project>

创建一个 controller

加上注解 @RefreshScope 表示该类要动态刷新
@Reference 是 dubbo 注解
@Value("${userName}") 中的 userName 是配置在 nacos 中的

@RestController
@RefreshScope  // 表示需要动态刷新
public class UserController {

    @Reference
    private UserMapper userMapper;

    @Value("${userName}")
    private String userName;

    @GetMapping("/userInfo")
    public String getUser(){
        return userMapper.getUserName(userName);
    }
}

启动类

@SpringBootApplication(scanBasePackages = "com.dubbo",
                       scanBasePackageClasses = com.netflix.client.config.DefaultClientConfigImpl.class)
@EnableDiscoveryClient
public class NacosDubboNacosConsumerApplication {

    public static void main(String[] args) {
        ApplicationContext con = SpringApplication.run(NacosDubboNacosConsumerApplication.class,args);
    }
}

nacos 的配置要配置在 bootstrap.yml 中

server:
  port: 8082

spring:
  application:
    name: nacos-dubbo-cousumer
  cloud:
    nacos:
      config:
        server-addr: 192.168.119.130:8848
      discovery:
        server-addr: 192.168.119.130:8848

dubbo:
  application:
    name: nacos-dubbo-cousumer
    #表示采用的dubbo协议
  protocol:
    name: dubbo
    #发布的端口号
    port: 20885
  ##### 调用服务超时时间
  consumer:
    timeout: 5000
  scan:
    base-packages: com.dubbo.controller

nacos 配置参数

image.png

启动 provider 和 consumer 项目访问

http://localhost:8082/userInfo
可以看到 nacos 中的配置信息被拿到了

image.png

nacos 配置中心使用

nacos Data ID

nacos 默认会使用 spring.application.name 的值称作为 Data Id,也就是默认会找 spring.spplicaiotn.name 对应的配置信息,默认是找 .properties 类型,可以通过 file-extension 来之定加载的配置类型

profiles 实现

prefix 默认为 spring.application.name 的值,可以通过配置项 spring.cloud.nacos.config.prefix 来配置
spring.profiles.active 为当前环境对应的 profile
当 spring.profiles.active 为空,dataId 的拼接格式变成 prefix . file-extension
当 spring.profiles.active 不为空,没找到 prefix - spring.profiles.active . file-extension,会找 prefix . file-extension,file-extension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置

设置 profiles 为 dev 环境
image.png
创建 nacos-dubbo-cousumer-dev.yml
image.png

此时 nacos 回去找 nacos-dubbo-cousumer-dev.yml 配置

Namespace / Group

新建 namespace
image.png
image.png
nacos 配置文件配置命名空间 ID
image.png
创建配置文件
image.png

此时会从新建的 namespace 中拿去配置

新建 order_group 分组
image.png
nacos 配置文件
image.png

此时会读取 order 跟组里的配置

配置共享配置

共享配置是指在同一个 namespace 下,有多个应用需要应用相同的配置,我们就可以定义共享配置

创建共享配置 common-1.yml
image.png
创建共享配置 common-2.yml
image.png
bootstrap.yml 配置
image.png
spring:
  application:
    name: nacos-dubbo-cousumer
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        server-addr: 192.168.245.131:8848
        # 指定配置文件的格式 默认是 .properties
        file-extension: yml
        # 命名空间ID
        namespace: c776f3d8-b095-4b49-9296-58460b942542
        # 自定义的 group
        group: order
        # 支持多个共享 Data Id 的配置,优先级小于extension-configs,自定义 Data Id 配置 属性是个集合,
        # 内部由 Config POJO 组成。Config 有 3 个属性,
        # 分别是 dataId
        #        group(默认为 DEFAULT_GROUP,如果 group = DEFAULT_GROUP ,那么 nacos Client 是可以实现自动刷新的)
        #        refresh(默认为 false,true 自动刷新)
        shared-configs[0]:
          data-id: common-1.yml
          group: COMMON_GROUP
          refresh: true
        shared-configs[1]:
          data-id: common-2.yml
          group: COMMON_GROUP
          refresh: true
      discovery:
        server-addr: 192.168.245.131:8848
controller 配置
@RestController
@RefreshScope  // 表示需要动态刷新
public class UserController {

    @Reference
    private UserMapper userMapper;

    @Value("${userName}")
    private String userName;

    @Value("${city}")
    private String city;
    @Value("${province}")
    private String province;

    @GetMapping("/userInfo")
    public String getUser(){
        return userMapper.getUserName(userName);
    }

    @GetMapping("/city")
    public String getCity(){
        return city;
    }

    @GetMapping("/province")
    public String getProvince(){
        return province;
    }
}
此时访问就会返回共享配置信息
image.png
image.png
上一篇下一篇

猜你喜欢

热点阅读