Spring + Tomcat项目中nacos配置中文乱码问题解决

实际工作的时候碰到了nacos中文乱码的问题,一顿排查最终还是调源码解决了。下面为具体的源码流程,有碰到的可以参考下。

对于nacos配置来说,初始主要源码就在NacosConfigService类中。里面有初始化获取配置content以及设置对应监听器的操作。具体可以参考:详解Nacos 配置中心客户端配置缓存动态更新的源码实现 - 简书

对于监听器,我们可以通过注解@NacosConfigListener去自定义监听器。但我们通@NacosValue注解配置的一些配置能进行动态刷新,就意味着nacos内部肯定有自定义的监听器,也是靠这个监听器进行数据的动态刷新。对应的类为NacosPropertySourcePostProcessor,具体的方法流程图如下:

addListenerIfAutoRefreshed -> receiveConfigInfo -> NacosPropertySource newNacosPropertySource = new NacosPropertySource(dataId, groupId, name, config, type);

上述初始化NacosPropertySource 的过程就是导致nacos配置中文乱码的原因
跟进初始化方法如下:
public NacosPropertySource(String dataId, String groupId, String name,
    String nacosConfig, String type) {
		super(name, toProperties(dataId, groupId, nacosConfig, type));
		this.type = type;
}


toProperties(dataId, groupId, nacosConfig, type) -> ConfigParseUtils.toProperties(dataId, group, text, type) -> toProperties(context, type) -> configParse.parse(context) 其中configParse为DefaultPropertiesConfigParse -> loader.load() -> load(true) -> OriginTrackedPropertiesLoader.CharacterReader reader = new OriginTrackedPropertiesLoader.CharacterReader(this.resource);


而其中异常原因就在new OriginTrackedPropertiesLoader.CharacterReader( this.resource) 这行代码中,点进去代码如下,其中编码格式为ISO_8859_1。导致中文解析就乱码。

我测试的nacos-spring-text版本如下,为1.0.0版本。在maven仓库中,这个版本显示是2020年发布的。

我尝试将nacos-spring-text版本更换为1.1.0后,可以看到在DefaultPropertiesConfigParse类中,CharacterReader类初始化后已经换成了StandardCharsets.UTF_8编码了,此时可以正常解析中文。

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-08 07:22:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-08 07:22:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-08 07:22:01       82 阅读
  4. Python语言-面向对象

    2024-02-08 07:22:01       91 阅读

热门阅读

  1. 1.2 Verilog 简介及发展历史

    2024-02-08 07:22:01       62 阅读
  2. visual studio注册码

    2024-02-08 07:22:01       54 阅读
  3. pydantic了解学习

    2024-02-08 07:22:01       48 阅读
  4. ThreadLocal在项目中的简单使用

    2024-02-08 07:22:01       54 阅读
  5. Cpp-3

    2024-02-08 07:22:01       53 阅读
  6. 贪心算法之找零钱

    2024-02-08 07:22:01       58 阅读
  7. 每天一个数据分析题(一百五十五)

    2024-02-08 07:22:01       60 阅读