使用 Spring 集成移入 GCP 存储后如何从本地目录中删除文件

How to remove file from local dir after moving in to GCP Storage using Spring Integration

我有这段代码,它成功地将文件从本地目录移动到 GCP 存储桶,但我需要在移动到 GCP 后删除它们。

@Bean
@InboundChannelAdapter(channel = "new-file-channel", poller = @Poller(fixedDelay = "5000"))
public MessageSource<File> streamingAdapter(Storage gcs) {
    FileReadingMessageSource sourceReader = new FileReadingMessageSource();
    sourceReader.setDirectory(new File(INPUT_DIR));
    sourceReader.setFilter(new SimplePatternFileListFilter(FILE_PATTERN));
    return sourceReader;
}

@Bean
@ServiceActivator(inputChannel = "new-file-channel")
public MessageHandler outboundChannelAdapter(Storage gcs) {
    GcsMessageHandler outboundChannelAdapter = new GcsMessageHandler(new GcsSessionFactory(gcs));
    outboundChannelAdapter.setRemoteDirectoryExpression(new ValueExpression<>(this.gcsReadBucket));
    return outboundChannelAdapter;
}

您需要向 @ServiceActivator(inputChannel = "new-file-channel") 添加一个 adviceChain 并引用 ExpressionEvaluatingRequestHandlerAdvice ,它将执行 onSuccessExpression 以删除该本地文件。

像这样:

    @Bean
    public Advice removeFileAdvice() {
        ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
        advice.setOnSuccessExpressionString("payload.delete()");
        advice.setSuccessChannel(myHandlerSuccessChannel());
        return advice;
    }

它将起作用,因为您的负载是 java.io.File 并且它具有 delete() 方法。

比起我一开始所说的配置:

@ServiceActivator(inputChannel = "new-file-channel", adviceChain="removeFileAdvice")