Stream closeable resource with Spring MVC

℡╲_俬逩灬. 提交于 2019-12-21 05:06:25

问题


After having read this article, I wish to use Spring to stream database query results directly to a JSON response to ensure constant-memory usage (no greedy loading of a List in memory).

Similar to what is done in the article with Hibernate, I assembled a greetingRepository object which returns a stream of the database contents based on a JdbcTemplate. In that implementation, I create an iterator over the queried ResultSet, and I return the stream as follows:

return StreamSupport.stream(spliterator(), false).onClose(() -> {
  log.info("Closing ResultSetIterator stream");
  JdbcUtils.closeResultSet(resultSet);
});

i.e. with an onClose() method guaranteeing that the underlying ResultSet will be closed if the stream is declared in a try-with-resources construct:

try(Stream<Greeting> stream = greetingRepository.stream()) {
  // operate on the stream
} // ResultSet underlying the stream will be guaranteed to be closed

But as in the article, I want this stream to be consumed by a custom object mapper (the enhanced MappingJackson2HttpMessageConverter defined in the article). If we take the try-with-resources need aside, this is feasible as follows:

@RequestMapping(method = GET)
Stream<GreetingResource> stream() {
  return greetingRepository.stream().map(GreetingResource::new);
}

However as a colleague commented at the bottom of that article, this does not take care of closing underlying resources.

In the context of Spring MVC, how can I stream from the database all the way into a JSON response and still guarantee that the ResultSet will be closed? Could you provide a concrete example solution?


回答1:


You could create a construct to defer the query execution at the serialization time. This construct will start and end the transaction programmaticaly.

public class TransactionalStreamable<T> {

    private final PlatformTransactionManager platformTransactionManager;

    private final Callable<Stream<T>> callable;

    public TransactionalStreamable(PlatformTransactionManager platformTransactionManager, Callable<Stream<T>> callable) {
        this.platformTransactionManager = platformTransactionManager;
        this.callable = callable;
    }

    public Stream stream() {
        TransactionTemplate txTemplate = new TransactionTemplate(platformTransactionManager);
        txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        txTemplate.setReadOnly(true);

        TransactionStatus transaction = platformTransactionManager.getTransaction(txTemplate);

        try {
            return callable.call().onClose(() -> {
                platformTransactionManager.commit(transaction);
            });
        } catch (Exception e) {
            platformTransactionManager.rollback(transaction);
            throw new RuntimeException(e);
        }
    }

    public void forEach(Consumer<T> c) {
        try (Stream<T> s = stream()){
            s.forEach(c);
        }
    }
}

Using a dedicated json serializer:

JsonSerializer<?> transactionalStreamableSer = new StdSerializer<TransactionalStreamable<?>>(TransactionalStreamable.class, true) {
    @Override
    public void serialize(TransactionalStreamable<?> streamable, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeStartArray();
        streamable.forEach((CheckedConsumer) e -> {
            provider.findValueSerializer(e.getClass(), null).serialize(e, jgen, provider);
        });

        jgen.writeEndArray();
    }
};

Which could be used like this:

@RequestMapping(method = GET)
TransactionalStreamable<GreetingResource> stream() {
  return new TransactionalStreamable(platformTransactionManager , () -> greetingRepository.stream().map(GreetingResource::new));
}

All the work will be done when jackson will serialize the object. It may be or not an issue regarding the error handling (eg. using controller advice).



来源:https://stackoverflow.com/questions/28830096/stream-closeable-resource-with-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!