亂碼介紹
在使用 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(); } }
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