Nacos——整合springboot详解

官方文档:https://nacos.io/zh-cn/docs/what-is-nacos.html
源码地址:https://github.com/ZeroClian/z-blog/tree/master/nacos


安装

standalone代表着单机模式运行,非集群模式

  • 关闭:sh shutdown.sh

❗️其他命令参考官方文档

整合Spring boot

  1. 引入依赖
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.4.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
</parent>
<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>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>2.1.4.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.1.4.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.1.4.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
  </dependency>
</dependencies>
  1. 修改 bootstrap.yml 配置文件
spring:
  application:
    name: nacos
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yml
      discovery:
        server-addr: 127.0.0.1:8848
  datasource:
    # 数据库
    url: jdbc:mysql://127.0.0.1:3306/zero-web?useUnicode=true&characterEncoding=UTF-8&useInformationSchema=true&enabledTLSProtocols=TLSv1.2&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

server:
  port: 8000

对应在配置中心的文件:
![image.png](https://img-blog.csdnimg.cn/img_convert/2da39566c968ab2fb78e417151efa39d.png#clientId=u31cc9576-39ed-4&from=paste&height=604&id=uc8a7cb5c&margin=[object Object]&name=image.png&originHeight=1208&originWidth=3904&originalType=binary&ratio=1&size=437253&status=done&style=none&taskId=u0986721d-3e09-44ca-a1a3-ad99d432f77&width=1952)

  1. 获取配置中心的配置
  • 自动获取
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {
    
    

    @Value("${spring.cloud.nacos.config.server-addr:127.0.0.1:8848}")
    private String serverAddr;
}
  • 手动获取:通过JavaSDK
@GetMapping("/get")
    @IgnoreResponseAdvice
    public String get() {
    
    
        try {
    
    
            String serverAddr = "127.0.0.1:8848";
            String dataId = "nacos-dev.yml";
            String group = "DEFAULT_GROUP";
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            ConfigService configService = NacosFactory.createConfigService(properties);
            String content = configService.getConfig(dataId, group, 5000);
            System.out.println(content);
            return content;
        } catch (NacosException e) {
    
    
            e.printStackTrace();
        }
        return "false";
    }
  1. 修改配置
/**
* 更新配置(不存在时创建配置)
*
* @param name
* @return
*/
@GetMapping("/update")
public Boolean updateConfig(String name) {
    
    
    try {
    
    
        // 初始化配置服务,控制台通过示例代码自动获取下面参数
        String serverAddr = "127.0.0.1:8848";
        String dataId = "nacos-dev.yml";
        String group = "DEFAULT_GROUP";
        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        String content = FileUtils.file2String("");
        boolean isPublishOk = configService.publishConfig(dataId, group, content, ConfigType.YAML.getType());
        System.out.println(isPublishOk);
        return true;
    } catch (Exception e) {
    
    
        e.printStackTrace();
    }
    return false;
}

文件上传工具类:

/**
 * 文件工具类
 *
 * @Author: qiyiguo
 * @Date: 2021-10-13 4:58 下午
 */
public class FileUtils {
    
    

    /**
     * 文件转为字符串
     *
     * @param
     * @return
     * @throws IOException
     */
    public static String file2String(String filePath) throws IOException {
    
    
        StringBuffer buffer = new StringBuffer();
        BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8));
        String s = null;
        //使用readLine方法,一次读一行
        while ((s = bf.readLine()) != null) {
    
    
            buffer.append(s + "\n");
        }
        return buffer.toString();
    }
}

未来:

  • 实现通过接口修改或获取配置文件
  • 增加管理页面,管理所有服务的配置文件

猜你喜欢

转载自blog.csdn.net/weixin_45636641/article/details/120784101