Nacos 多命名空间读不到该空间配置?Or 注册不到指定命名空间上?

前言

记录一个自己前段时间遇到的问题,希望能够帮到出现同样问题的读者

这里创建了一个新的命名空间,想要对在该命名空间上的服务与其他命名空间进行隔离。

在网上翻阅其他作者的资料只解决了标题问题的其中一个。

正确的做法:

需要在配置文件中做修改

spring:
  application:
    name: xxxx
  cloud:
    nacos:
      server-addr: xxx:8848
      config:
        namespace: a7d702ec-994e-4578-9155-8ccff5cf0674
        shared-configs:
          # 加载配置
      username: xxx
      password: xxx
      discovery:
        namespace: a7d702ec-994e-4578-9155-8ccff5cf0674
        ip: xxx

可以看到,无论在 config 中还是 discovery 中,都需要配置 namespace

  • config 中:配置加载对应命名空间的配置
  • discovery 中:配置服务暴露在那个命名空间

ps:在配置的值是  命名空间id,而不是 命名空间名称。可以进行编辑

结论

可见 Nacos 将配置和暴露的位置进行分开配置,这样能进一步提高配置加载的灵活性。在一个命名空间的服务能够加载不同命名空间的配置,提高配置复用性。

用户可以根据需求配置这两项参数,不一定要在同一命名空间下

### Nacos 数据源配置方法及示例 #### 使用AOP + 注解方式切换数据源并将其配置移至Nacos 为了实现动态的数据源管理和热更新功能,在项目中引入了面向切面编程(AOP)以及自定义注解来灵活地指定不同场景下的数据源[^1]。 对于`DruidDataSource`类型的连接池而言,可以通过Spring Cloud Alibaba Nacos Config模块轻松完成外部化配置工作。这使得应用程序能够在不停机的情况下调整数据库链接属性,从而提高了系统的灵活性和可维护性[^3]。 以下是具体的实践步骤: - **创建自定义注解** 定义一个名为`@TargetDataSource`的Java注解用于标记需要特殊处理的方法或类级别上的目标数据源名称。 ```java import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD, ElementType.TYPE }) public @interface TargetDataSource { String value(); } ``` - **编写AOP逻辑** 编写一个实现了`MethodInterceptor`接口的拦截器类,该类负责解析上述提到的注解并将相应的数据源设置到当前线程上下文中以便后续操作可以访问正确的资源实例。 ```java @Component @Aspect @Slf4j public class DataSourceSwitchingInterceptor implements MethodInterceptor { private final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>(); public Object invoke(MethodInvocation invocation) throws Throwable { Class<?> targetClass = invocation.getThis().getClass(); Method specificMethod = getSpecificMethod(targetClass, invocation.getMethod()); // Determine the data source name from annotations on method or type level. Optional.ofNullable(specificMethod.getDeclaredAnnotation(TargetDataSource.class)) .or(() -> Optional.ofNullable( targetClass.getDeclaredAnnotation(TargetDataSource.class))) .ifPresent(annotation -> setDataSourceName(annotation.value())); try { return invocation.proceed(); // Proceed with actual business logic execution. } finally { clearDataSourceName(); // Clean up after finishing processing request. } } protected void setDataSourceName(String dsName){ log.debug("Setting current thread's datasource to {}", dsName); this.contextHolder.set(dsName); } protected void clearDataSourceName(){ log.debug("Clearing current thread's datasource."); this.contextHolder.remove(); } /** * Helper function that retrieves a more concrete implementation of given abstract/base method, * which may carry additional metadata like custom annotations we're interested in here. */ private static Method getSpecificMethod(Class<?> clazz, Method baseMethod) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(baseMethod, "Method must not be null"); try { return clazz.getDeclaredMethod(baseMethod.getName(), baseMethod.getParameterTypes()); } catch (NoSuchMethodException e) { throw new IllegalStateException(e.getMessage(), e); } } } ``` - **配置多数据源支持** 修改项目的主配置文件(`application.yml`)以声明多个不同的数据源bean,并通过条件注入的方式让它们根据实际情况生效。 ```yaml spring: cloud: nacos: config: server-addr: localhost:8848 file-extension: yaml group: DEFAULT_GROUP shared-configs: - data-id: druid-datasource-primary.yaml refresh: true - data-id: druid-datasource-secondary.yaml refresh: true ``` - **在Nacos中添加数据源配置** 登录Nacos控制台界面,按照提示新建两个独立于应用本身的YAML格式配置项分别命名为`druid-datasource-primary.yaml` 和 `druid-datasource-secondary.yaml`, 将其内容填充为如下所示: ```yaml # Primary Data Source Configuration spring.datasource.dynamic.primary.url=jdbc:mysql://localhost:3306/primary_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=Asia/Shanghai spring.datasource.dynamic.primary.username=root spring.datasource.dynamic.primary.password=password spring.datasource.dynamic.primary.driver-class-name=com.mysql.cj.jdbc.Driver # Secondary Data Source Configuration spring.datasource.dynamic.secondary.url=jdbc:mysql://localhost:3307/secondary_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=Asia/Shanghai spring.datasource.dynamic.secondary.username=root spring.datasource.dynamic.secondary.password=password spring.datasource.dynamic.secondary.driver-class-name=com.mysql.cj.jdbc.Driver ``` 以上就是利用Nacos作为集中式的配置管理中心来进行微服务体系下分布式事务管理的一个典型应用场景介绍[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

durancer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值