如何使用Spring Integration SFTP设置文件名与时间戳?
使用SpEL为SftpOutputGateway设置带时间戳的文件名
核心思路
通过SftpOutputGateway(或对应SftpMessageHandler)的filenameExpression属性,结合SpEL表达式生成包含动态时间戳的文件名,核心是利用SpEL的T()语法调用Java时间API生成格式化后的时间字符串。
具体实现示例
1. Java配置类方式(推荐)
@Bean public SftpMessageHandler sftpMessageHandler(SftpSessionFactory sessionFactory) { SftpMessageHandler handler = new SftpMessageHandler(sessionFactory); // 生成格式为 data_20240520143022.txt 的文件名 handler.setFilenameExpressionString( "'data_' + T(java.time.LocalDateTime).now().format(T(java.time.format.DateTimeFormatter).ofPattern('yyyyMMddHHmmss')) + '.txt'" ); handler.setRemoteDirectoryExpressionString("'/remote/storage'"); return handler; }
- 说明:
T(java.time.LocalDateTime):SpEL中调用静态类的语法now():获取当前本地时间format(...):用指定的日期格式化器生成字符串- 单引号包裹的部分是固定字符串,与动态生成的时间戳拼接
2. 结合消息属性的动态文件名
如果需要结合消息头或消息体中的业务属性(比如订单ID),可直接在SpEL中引用:
handler.setFilenameExpressionString( "'order_' + headers['orderId'] + '_' + T(java.time.LocalDateTime).now().format(T(java.time.format.DateTimeFormatter).ofPattern('yyyyMMddHHmmss')) + '.csv'" );
这里headers['orderId']会读取消息头中名为orderId的属性值,和时间戳拼接成最终文件名。
3. XML配置方式
如果使用Spring XML配置,语法逻辑一致:
<int-sftp:outbound-gateway session-factory="sftpSessionFactory" request-channel="sftpOutChannel" command="put" filename-expression="'report_' + T(java.time.LocalDateTime).now().format(T(java.time.format.DateTimeFormatter).ofPattern('yyyyMMddHHmmss')) + '.pdf'" remote-directory="/remote/reports"/>
注意:XML中单引号需用'转义,若格式包含分隔符:
filename-expression="'report_' + T(java.time.LocalDateTime).now().format(T(java.time.format.DateTimeFormatter).ofPattern('yyyy-MM-dd_HH-mm-ss')) + '.pdf'"
额外注意事项
- 时区支持:若需要UTC时间,替换时间获取逻辑为
T(java.time.ZonedDateTime).now(T(java.time.ZoneId).of('UTC')) - 时间格式:可根据需求调整
DateTimeFormatter的模式,比如yyyyMMdd(仅日期)、HHmmss(仅时间)等 - 旧版本兼容:若使用Java 8之前的版本,可改用
T(java.util.Date)结合SimpleDateFormat,但推荐使用Java 8+的时间API
内容的提问来源于stack exchange,提问作者Choff
相关产品推荐
相关产品推荐

