侧边栏壁纸
博主头像
樯哥的技术分享网博主等级

学无止境,学以致用,志存高远。

  • 累计撰写 17 篇文章
  • 累计创建 10 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

SpringCloud Nacos 配置中心

随心
2023-06-14 / 0 评论 / 0 点赞 / 73 阅读 / 10288 字

一、微服务简单了解


传统单应用项目主要缺点:整个系统涵盖的功能特别多,甚至是把整个公司业务都集中到了一个应用程序。比如前台和后台是一个项目中,如果要更新后台会导致前台项目也不可用。并且,当应用不足以支撑高并发时,除了部署多套服务再使用nginx多搞几个负载均衡外,几乎毫无办法。
微服务就是将传统单应用项目分割为多个项目,扩展起来更加容易,但是增加了部署项目的复杂度,现如今,各种流水线式的部署手段也非常成熟,使用容器化部署多个服务也变得非常容易。


二、配置中心


微服务因为有很多个应用程序,因此将每个应用程序的配置文件集中到一个单独的应用程序中进行管理往往事半功倍,因此也就出现了各种配置中心。比如,Spring Cloud Config组件,可以将配置通过git之类的版本管理工具进行统一管理。我们这里使用功能更强大的nacos作为配置中心,因为nacos本身就是一个配置中心的服务端,我们无需再额外编写一个配置中心的服务端,使用起来更加方便,同时nacos还是一个注册中心,后续也会使用到。

安装nacos

  1. 点击这里下载 解压后进入bin目录,使用记事本打开startup.cmd文件,大约25行左右的位置,找到set MODE="***" 的代码,修改为:set MODE="standalone" ,作用是修改为单机模式启动,默认是集群模式,开发情况下我们使用单机模式。

  2. 切换到conf目录,找到mysql-schema.sql文件,该文件是MySQL数据库初始化脚本,然后我们创建一个nacos_config的数据库,并使用该脚本初始化。

  3. 修改application.properties文件,主要是启用MySQL数据库,并且修改数据库地址,然后启用鉴权。下面是部分需要修改的片段:

    ### If use MySQL as datasource:
    ### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced.
    spring.datasource.platform=mysql
    spring.sql.init.platform=mysql
    
    ### Count of DB:
    db.num=1
    
    ### Connect URL of DB:
    db.url.0=jdbc:mysql://localhost:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
    db.user.0=root
    db.password.0=123456
    ### If turn on auth system:
    nacos.core.auth.enabled=true
    
    ### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay.
    nacos.core.auth.caching.enabled=true
    
    ### Since 1.4.1, Turn on/off white auth for user-agent: nacos-server, only for upgrade from old version.
    nacos.core.auth.enable.userAgentAuthWhite=false
    
    ### Since 1.4.1, worked when nacos.core.auth.enabled=true and nacos.core.auth.enable.userAgentAuthWhite=false.
    ### The two properties is the white list for auth and used by identity the request from other server.
    nacos.core.auth.server.identity.key=example
    nacos.core.auth.server.identity.value=example
    
    ### worked when nacos.core.auth.system.type=nacos
    ### The token expiration in seconds:
    nacos.core.auth.plugin.nacos.token.cache.enable=false
    nacos.core.auth.plugin.nacos.token.expire.seconds=18000
    ### The default token (Base64 String):
    nacos.core.auth.plugin.nacos.token.secret.key=VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=
  4. 进入bin目录,运行startup.cmd即可启动。访问http://127.0.0.1:8848/nacos/index.html#/login ,用户名和密码都是nacos。

  5. 点击命名空间,创建一个新的命名空间,记住命名空间id。

    创建命名空间.png

使用配置中心

  1. 创建一个springboot项目:

    下面是pom.xml文件配置,根据情况自行修改:注意命名空间就是上图中新创建的命名空间id。

    <?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>3.1.0</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>demo</name>
        <description>demo</description>
    
        <properties>
            <java.version>17</java.version>
            <spring-cloud.version>2022.0.3</spring-cloud.version>
            <spring.cloud.alibaba.version>2022.0.0.0-RC2</spring.cloud.alibaba.version>
        </properties>
        <dependencies>
            <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>
        </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.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                            </exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        <profiles>
            <profile>
                <id>dev</id>
                <activation>
                    <activeByDefault>true</activeByDefault>
                </activation>
                <properties>
                    <!-- 开发环境 -->
                    <profile.name>dev</profile.name>
                    <!--nacos服务访问地址-->
                    <nacos.server-addr>127.0.0.1:8848</nacos.server-addr>
                    <!--命名空间id-->
                    <nacos.namespace>75d49a80-72f9-4b15-97b8-08ad100100b0</nacos.namespace>
                    <!--nacos用户名和密码-->
                    <nacos.username>nacos</nacos.username>
                    <nacos.password>nacos</nacos.password>
                </properties>
            </profile>
        </profiles>
    
    </project>
    
  2. 启动类如下:

    package com.example.demo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication
    @RestController
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
        //该配置从配置中心读取,读取不到的话使用默认值hello world
        @Value("${value:hello world}")
        String value;
    
        @GetMapping("/")
        public String test() {
            return value;
        }
    }
  3. application.yaml文件配置如下:如有不懂,可以看注释,optional:nacos:${spring.application.name}.yaml 表示从nacos的dataId为service-test-config.yaml的配置中读取配置。

    server:
      port: 8000
    spring:
      application:
        name: service-test-config
      cloud:
        nacos:
          username: @nacos.username@ #@***@这种写法表示从pom.xml文件读取配置
          password: @nacos.password@
          config:
            file-extension: yaml
            server-addr: @nacos.server-addr@ #用于管理配置的nacos服务地址
            namespace: @nacos.namespace@ #命名空间
      config:
        import: #springboot3必须配置此选项,至少配置一个,可以任意配置,配置后会使用nacos配置中心对应的配置
          - optional:nacos:${spring.application.name}.yaml #前面加optional表示可选,允许配置服务器连接不成功时启动服务
  4. 此时访问localhost:8000,会看见hello world,因为此时没有读取到配置,所以会显示默认值。

  5. 进入nacos控制台,然后切换到刚才创建的命名空间下,创建配置,注意要切换命名空间。

    创建配置.jpg
    创建配置2.png

  6. 此时再访问localhost:8000,会看见hello world,因为此时配置更新之后该程序并不能实时生效,但是我们如果重启项目,程序会在启动时去nacos读取配置,因此我们可以重新启动后,再访问localhost:8000,看见配置生效了。如果我们要想让配置修改后实时生效,可以在使用该配置的类上使用注解@RefreshScope即可。

    @SpringBootApplication
    @RestController
    //实时刷新
    @RefreshScope
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
        //该配置从配置中心读取,读取不到的话使用默认值hello world
        @Value("${value:hello world}")
        String value;
    
        @GetMapping("/")
        public String test() {
            return value;
        }
    }
0

评论区