处理后的Spring集成移动文件

时间:2016-11-16 05:57:48

标签: spring-integration polling

如何在处理文件后在spring集成中处理后移动文件..? 我已经跟着http://xpadro.blogspot.com/2016/07/spring-integration-polling-file.html来实现文件轮询,但我需要添加onSuccess和OnError跨国事件(没有XML配置)

1 个答案:

答案 0 :(得分:6)

我不确定“交易”是什么意思,文件系统通常不是事务性的,但您可以在流程中向最终消费者添加建议......

@SpringBootApplication
public class So40625031Application {

    public static void main(String[] args) {
        SpringApplication.run(So40625031Application.class, args);
    }

    @Bean
    public IntegrationFlow flow() {
        return IntegrationFlows.from(
                    Files.inboundAdapter(new File("/tmp/foo")), e -> e.poller(Pollers.fixedDelay(1000)))
                .transform(Transformers.fileToString())
                .handle("processor", "process", e -> e.advice(advice()))
                .get();
    }

    @Bean
    public Processor processor() {
        return new Processor();
    }

    @Bean
    public AbstractRequestHandlerAdvice advice() {
        return new AbstractRequestHandlerAdvice() {

            @Override
            protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
                File file = message.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class);
                try {
                    Object result = callback.execute();
                    file.renameTo(new File("/tmp/bar", file.getName()));
                    System.out.println("File renamed after success");
                    return result;
                }
                catch (Exception e) {
                    file.renameTo(new File("/tmp/baz", file.getName()));
                    System.out.println("File renamed after failure");
                    throw e;
                }
            }
        };
    }

    public static class Processor {

        public void process(String in) {
            System.out.println(in);
        }

    }

}