【问题标题】:Reactive way of reading YAML with Jackson using Spring boot webflux使用 Spring boot webflux 与 Jackson 一起读取 YAML 的反应式方法
【发布时间】:2021-08-11 01:06:18
【问题描述】:

配置中的yamlObjectMapper

@Bean
    public ObjectMapper yamlObjectMapper() {
        ObjectMapper yamlObjectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature
            .WRITE_DOC_START_MARKER));
        yamlObjectMapper.findAndRegisterModules();
        return yamlObjectMapper;
    }

解析yaml文件的服务

@Service
public class CustomerService {      

  @Autowired
  @Qualifier("yamlObjectMapper")
  private ObjectMapper yamlObjectMapper;

  public Customer get() {
    try {          
      InputStream inputStream = ResourceUtils.getURL("classpath:/files/test.yaml").openStream();
      return yamlObjectMapper.readValue(inputStream, Customer.class);
    } catch (IOException ex) {
      throw new IllegalStateException(ex);
    }
  }

  @Data
  public static class Customer {
    private String name;
    private String surname;
    private String email;
  }
}

我猜 IO 操作是阻塞的,如何使用响应式方式来完成?

【问题讨论】:

  • 我不认为你可以轻易做到非阻塞,所以你最好的办法是用Mono.fromCallable包装代码块并将工作移动到一个用于阻塞的线程池,如.subscribeOn(Schedulers.boundedElastic())
  • @MartinTarjányi 谢谢,你能展示完整的例子吗

标签: spring-boot spring-webflux project-reactor jackson-dataformat-yaml


【解决方案1】:

我宁愿使用配置绑定,因为您可能需要阅读一次。

package com.vob.webflux.webfilter.controller;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = "classpath:config.yml", factory= YamlPropertySourceFactory.class)
@Getter
public class YamlFooProperties {
    @Value("${test}")
    private String test;
}

工厂

package com.vob.webflux.webfilter.controller;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
            throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());

        Properties properties = factory.getObject();

        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
    }
}

来源factory from

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 2020-04-05
    • 2018-06-24
    • 2021-11-22
    • 2019-01-05
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多