【Nacos系列第三篇】- Nacos之Spring Boot Config

简介: 作者:毕来生 【Nacos系列第三篇】- Nacos之Spring Boot Config

作者:毕来生

前言

​ 个人比较看好Spring Cloud Alibaba家族。此系列以Nacos为主题,从Spring、Spring boot、Spring Cloud多个方面逐步进行演示,源码解读。目前来看官方文档还有待完善。网络上除了官网外缺少Nacos系列文章。都是零零散散的知识点。如此系列文章哪里写的有不周全,错误之处。欢迎大家指正。谢谢。

​ 因公众号排版问题,可能会有代码显示不完整,请使用电脑版微信内置浏览器/复制链接到浏览器中。

​ 第一篇 : 【Nacos系列第一篇】-Nacos之Spring Discovery 以及Config

​ 第二篇 : 【Nacos系列第二篇】-Nacos之Spring Boot Discovery。

​ 因大家在工作中逐步以Spring boot、Spring Cloud为主进行开发。我们接下来会以这两个为核心演示详解。


Nacos架构图

在这里插入图片描述

工程结构

上面说了那么多,现在先来看一下我们的Spring boot Nacos config工程结构(Windows下演示)

Spring Boot版本:2.1.2.RELEASE

在这里插入图片描述

准备工作

1、启动Nacos(Demo演示环境为Windows下)

2、访问http://127.0.0.1:8848/nacos/index.html#/configurationManagement?dataId=&group=&appName=&namespace= 进入Nacos配置管理页面

3、点击左侧配置管理->配置列表(右侧有一个加号。添加对应信息),如下图

在这里插入图片描述

在这里插入图片描述

以上就是我们要做的准备工作啦。


获取ConfigService方法

1、通过@NacosInjected注解获取

@NacosInjected
ConfigService configService;

2、通过NacosFactory传入Properties获取

ConfigService configService = NacosFactory.createConfigService(properties);

3、通过NacosFactory传入ServerAddr获取

ConfigService configService = NacosFactory.createConfigService(serverAddr);

以上方式均是为反射获取,NacosFactory创建ConfigService实际上也是调用ConfigFactory.createConfigService实现的

    /**
     * Create config
     * 
     * @param properties
     *            init param
     * @return config
     * @throws NacosException
     *             Exception
     */
    public static ConfigService createConfigService(Properties properties) throws NacosException {
        return ConfigFactory.createConfigService(properties);
    }

附上创建ConfigService源码

    /**
     * Create Config
     * 
     * @param ServerAddr
     *            serverlist
     * @return Config
     * @throws NacosException
     *             Exception
     */
    public static ConfigService createConfigService(String serverAddr) throws NacosException {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        try {
            Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.config.NacosConfigService");
            Constructor constructor = driverImplClass.getConstructor(Properties.class);
            ConfigService vendorImpl = (ConfigService) constructor.newInstance(properties);
            return vendorImpl;
        } catch (Throwable e) {
            throw new NacosException(-400, e.getMessage());
        }
    }

代码演示

附上与普通创建的Spring boot工程不同点(以下演示为通过配置管理代码示例中相同获取方式)

ConfigController(新增)

package org.nacos.springboot.controller;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author bilaisheng
 * @wechat: 878799579
 * @date 2019/01/15 19:34
 * @description  Test Nacos Config
 */
@Controller
@RequestMapping("config")
public class ConfigController {

    /**
     * @author : bilaisheng
     * @wechat: 878799579
     * @date : 2019/01/15 19:45
     * @return Map
     * @throws NacosException
     * @throws InterruptedException
     */
    @ResponseBody
    @RequestMapping("/get")
    public Map getConfig() throws NacosException, InterruptedException {
        // 用以演示用,页面返回数据展示
        Map map = new HashMap();
        //  服务地址。本机演示故写localhost。请根据实际情况替换对应IP
        String serverAddr = "localhost";
        String dataId = "nacos-spring";
        String group = "bilaisheng";
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        // 创建ConfigService,此处通过Properties方式进行创建,另一种演示serviceaddr获取configService.
        // 原理上都是通过 ConfigFactory.createConfigService()去进行创建
        ConfigService configService = NacosFactory.createConfigService(properties);
        // ConfigService configService = NacosFactory.createConfigService(serverAddr);

        String content = configService.getConfig(dataId, group, 5000);
        System.out.println("config : " + content);
        map.put("content", content);
        // 添加Listener,用以演示receive获取数据结果
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("recieve : " + configInfo);
            }
            @Override
            public Executor getExecutor() {
                return null;
            }
        });

        // 推送config。将原有dataid中信息替换。
        boolean isPublishOk = configService.publishConfig(dataId, group, "publish config content");
        System.out.println("isPublishOk : " + isPublishOk);
        map.put("isPublishOk", isPublishOk);

        Thread.sleep(3000);
        content = configService.getConfig(dataId, group, 5000);
        System.out.println("Thread sleep 3000ms : " + content);
        map.put("Thread sleep 3000ms : ", content);

        // 删除指定dataid , group 配置
        boolean isRemoveOk = configService.removeConfig(dataId, group);
        System.out.println("remove " + dataId + "config is " + isRemoveOk);
        Thread.sleep(3000);

        content = configService.getConfig(dataId, group, 5000);
        System.out.println("content after 5000ms "+content);
        Thread.sleep(3000);
        return map;
    }
}

application.properties

nacos.config.server-addr=127.0.0.1:8848

pom.xml

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

<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>0.2.1</version>
</dependency>

上述内容就是我们在创建好Spring Boot工程结构后增加/调整内容。

演示步骤

1、启动 BilaishengNacosSpringbootConfigApplication

2、调用 http://localhost:8080/config/get,此时控制台出现

在这里插入图片描述

页面出现

在这里插入图片描述

以上就是我们Spring Boot Config的一个Demo例子


喜欢就关注我吧

在这里插入图片描述

目录
相关文章
|
3月前
|
人工智能 Java Nacos
基于 Spring AI Alibaba + Nacos 的分布式 Multi-Agent 构建指南
本文将针对 Spring AI Alibaba + Nacos 的分布式多智能体构建方案展开介绍,同时结合 Demo 说明快速开发方法与实际效果。
3156 68
|
4月前
|
XML Java Nacos
Spring Boot 整合Nacos 版本兼容适配 史上最详细文档
本文介绍SpringBoot整合Nacos的完整流程,涵盖Nacos下载安装、配置中心与服务发现集成、版本兼容性问题及实战配置。重点解决SpringBoot 3.3.0与Nacos版本适配难题,推荐使用Spring Cloud Alibaba方案,并提供项目开源地址供参考学习。
|
6月前
|
Dubbo 数据可视化 Java
整合SpringBoot、Dubbo与Nacos:一个快速入门教程
经过上述步骤,消费者模块成功引用了生产者提供的服务,并通过Spring Web将服务映射到了特定的URL路径上。消费者模块成功地调用并展示了生产者提供的数据,并在不移除特定依赖项的情况下确保了系统的正常运行。
|
XML Java 应用服务中间件
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
2884 17
Spring Boot 两种部署到服务器的方式
|
11月前
|
Cloud Native Java Nacos
springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析
通过本文,我们详细介绍了如何在 Spring Cloud 和 Spring Boot 中集成 Nacos 进行服务注册和配置管理,并对 Nacos 的源码进行了初步分析。Nacos 作为一个强大的服务注册和配置管理平台,为微服务架构提供
4509 14
|
监控 Java Nacos
使用Spring Boot集成Nacos
通过上述步骤,Spring Boot应用可以成功集成Nacos,利用Nacos的服务发现和配置管理功能来提升微服务架构的灵活性和可维护性。通过这种集成,开发者可以更高效地管理和部署微服务。
4090 17
|
10月前
|
Java 数据库 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
429 0
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
878 2