springcloud config自动刷新中文乱码问题


乱码介绍

在使用 spring cloud config 时,如果在 git仓库中的properties 文件里面有中文的话,会出现乱码。


乱码的原因是:spring 默认使用org.springframework.boot.env.PropertiesPropertySourceLoader 来加载配置,底层是通过调用 Properties 的 load 方法,而load方法输入流的编码是 ISO 8859-1

 

解决方法:

1. 实现org.springframework.boot.env.PropertySourceLoader 接口,重写 load 方法

@Slf4j
public class MyPropertiesHandler implements PropertySourceLoader {

    @Override
    public String[] getFileExtensions() {
        return new String[]{"properties", "xml"};
    }

    @Override
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        Map<String, ?> properties = loadProperties(resource);
        if (properties.isEmpty()) {
            return Collections.emptyList();
        }
        return Collections.singletonList(new OriginTrackedMapPropertySource(name, properties));
    }


    private Map<String, ?> loadProperties(Resource resource) throws IOException {
        String filename = resource.getFilename();
        if (filename != null && filename.endsWith(".xml")) {
            return (Map) PropertiesLoaderUtils.loadProperties(resource);
        }
        return new OriginTrackedPropertiesLoader(resource).load();
    }
}
View Code

 

2.上述代码中用的OriginTrackedPropertiesLoader类为spring框架中的,将该类直接复制到本地,并将157行的ISO8859-1编码修改为utf-8,并在自己实现的类中使用本地的OriginTrackedPropertiesLoader,

 

 


3.在 resources下新建 META-INF 文件夹,新建一个 spring.factories 文件

org.springframework.boot.env.PropertySourceLoader=com.***.***.MyPropertiesHandler

上述改动均需要放在config server端,config client端不做任何改动。

 

 

4.application.yaml中 增加如下配置:

  server.tomcat.uri-encoding=utf-8

 spring.http.encoding.charset=utf-8

 spring.http.encoding.enabled=true

 spring.http.encoding.force=true

management.endpoint.health.show-details : always

management.endpoints.web.exposure.include: ${prometheus,refresh}

大功告成,但愿能拯救水深火热的广大猿友!

 

自动刷新:

1. 在config client项目中增加 相关actuator jar包

gradle方式:  compile ‘org.springframework.boot:spring-boot-starter-actuator’

maven方式: 吧啦吧啦

2.  在使用到配置参数的类上 增加@RefreshScope

3. 修改完配置文件里的参数后,需要调用 服务层的 刷新接口:  http://localhost:port/actuator/refresh

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM