2016-11-16 44 views

回答

4

我不知道你所說的「交易」的意思,文件系統通常是不能交易的,但您可以在流程中向最終消費者添加建議...

@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); 
     } 

    } 

} 
+0

這正是我所期待的。感謝您的解決方案。 –

+1

當我用'Transformers.fromJson(My.class)'替換'Transformers.fileToString()'時,它無法正常工作,以便從文件中直接讀取JSON對象。 JSON轉換器丟失了文件名頭。在'from(Files ...)'之後添加'.enrichHeaders(h - > h.headerExpression(FileHeaders.ORIGINAL_FILE,「payload」))'以使其工作。 –