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

 

posted @ 2019-07-12 17:49  西凤楼  阅读(2038)  评论(1编辑  收藏  举报
如果,您认为阅读这篇博客让您有些收获, 如果,您希望更容易地发现我的新博客,不妨关注一下。因为,我的写作热情也离不开您的肯定支持。 感谢您的阅读,如果您对我的博客所讲述的内容有兴趣,请继续关注我的后续博客。 因为有小孩,兼职卖书,路过的朋友有需要低价购买图书、点读笔、纸尿裤等资源的,可扫最上方二维码,质量有保证,价格很美丽,欢迎咨询!