栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Nacos 多环境配置共享

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Nacos 多环境配置共享

开发、生产、测试中的配置属性是一样的,那就需要配置共享,修改一次,多环境都可使用,而不需要多环境都修改。

微服务启动时会从Nacos读取多个配置文件:

  1. [spring.application.name]-[spring.profile.active].yaml,如userservice-dev.yaml
  2. [spring.application.name].yaml,如userservice.yaml

无论profile如何变化,[spring.application.name].yaml这个文件一定会加载,因此多环境共享配置可以写入这个文件。

添加userservice.yaml配置

配置内容为

pattern:
  envSharedValue: wow

修改配置类
添加private String envSharedValue;

package com.yy.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
//添加get与set方法
@Component
//将此类注入成一个Bean
@ConfigurationProperties(prefix = "pattern")
//前缀与变更加起来,匹配对应配置文件
public class PatternProperties {
    private String dateformat;
    private String envSharedValue;
}

修改Controller
package com.yy.controller;

import com.yy.config.PatternProperties;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/user")
//@RefreshScope
public class UserController {

// @Value("${pattern.dateformat}")
// private String dateformat;

@Autowired
private PatternProperties patternProperties;

@GetMapping("now")
public String now(){

// return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(patternProperties.getDateformat()));
}

@GetMapping("prop")
public PatternProperties patternProperties(){

// return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
return patternProperties;
}
}

对应bootstrap.yml文件

spring:
  application:
    name: userservice
  profiles:
    active: dev # 环境
  cloud:
    nacos:
      server-addr: localhost:8848 # nacos地址
      config:
        file-extension: yaml # 文件后缀名

复制userservice
添加port与profiles

启动访问
可看见test无法访问到userservice-dev.yaml中的配置内容。



日志区别
同时日志也可以看出区别,dev加载了两个配置,test只加载了一个配置

多种配置优先级
同一个配置属性,存在三个文件中,优先级如下:
服务名-profile.yaml > 服务名称.yaml > 本地配置

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/631049.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号