记录Spring Cloud Config 使用中遇到的坑

本文探讨了Spring Cloud配置文件中文乱码问题的解决方案,以及客户端和服务端依赖配置的注意事项。重点介绍了自定义PropertySourceLoader处理中文编码,并提醒避免client引入service依赖。
摘要由CSDN通过智能技术生成

一.无法获取到配置文件

1.git上面的文件名只能为 {application}-{profile}.yml 或 {application}-{profile}.properties(注: {application} 要与项目中微服务名称一直既spring.application.name的值,{profile}就是配置文件的版本,项目有开发版本、测试环境版本、生产环境版本等)

2.config client maven依赖为

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

config service maven依赖为

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>

注意!!!

client中千万千万不能引入service的依赖!

client中千万千万不能引入service的依赖!

client中千万千万不能引入service的依赖!

二.配置文件中文乱码

乱码的原因

spring 默认使用 org.springframework.boot.env.PropertiesPropertySourceLoader 来加载配置,底层是通过调用 Properties 的 load 方法,而load方法输入流的编码是 ISO 8859-1 ,所以会出现中文乱码问题。

解决方式

自定义属性源加载器,实现 PropertySourceLoader 接口

public class MyPropertiesHandler implements PropertySourceLoader {

    private static final Logger logger = LoggerFactory.getLogger(MyPropertiesHandler.class);

    @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) {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = resource.getInputStream();
            properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); // 设置为UTF-8
            inputStream.close();
        } catch (IOException e) {
            logger.error("load inputstream failure...", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("close IO failure ....", e);
                }
            }
        }
        return (Map) properties;
    }
}

在 resources 文件夹下,创建 META-INF 文件夹,再创建 spring.factories 文件

# 修改系统内置的编码,值为你实现 PropertySourceLoader 接口的类路径
org.springframework.boot.env.PropertySourceLoader=com.example.config.MyPropertiesHandler


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值