zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Yarn下分片和分块源代码分析
    Yarn下Map数控制
    hadoop中使用的Unsafe.java
    hbase的coprocessor使用(转)
    eclipse插件
    短线及时发现个股机会的七大招数
    hadoop分类输出
    安装ubuntu-tweak
    rabbitmq安装使用
    “-Xmx1024m -Xms1024m -Xmn512m -Xss256k”——Java运行参数(转)
  • 原文地址:https://www.cnblogs.com/xifenglou/p/11177581.html
Copyright © 2011-2022 走看看