Как проверить контрольную сумму файла, загруженного с помощью Spring SFTP
В нашем приложении огромное количество файлов, загруженных с удаленного компьютера на локальный компьютер (сервер, на котором выполняется код). Мы решили использовать Spring SFTP для загрузки. Используя приведенный ниже код, я могу загрузить файл с удаленного компьютера на локальный.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/sftp http://www.springframework.org/schema/integration/sftp/spring-integration-sftp.xsd">
<import resource="SftpSampleCommon.xml"/>
<int:gateway id="downloadGateway" service-interface="com.rizwan.test.sftp_outbound_gateway.DownloadRemoteFileGateway"
default-request-channel="toGet"/>
<int-sftp:outbound-gateway id="gatewayGet"
local-directory="C:\Users\503017993\Perforce\rizwan.shaikh1_G7LGTPC2E_7419\NGI\DEV\Jetstream_Branches\C360_Falcon2_1_Main\sftp-outbound-gateway"
session-factory="sftpSessionFactory"
request-channel="toGet"
remote-directory="/si.sftp.sample"
command="get"
command-options="-P"
expression="payload"
auto-create-local-directory="true"
session-callback="downloadCallback">
<int-sftp:request-handler-advice-chain>
<int:retry-advice />
</int-sftp:request-handler-advice-chain>
</int-sftp:outbound-gateway>
<!-- reply-channel="toRm" -->
<int:gateway id="deleteGateway" service-interface="com.rizwan.test.sftp_outbound_gateway.DeleteRemoteFileGateway"
default-request-channel="toRm"/>
<int-sftp:outbound-gateway id="gatewayRM"
session-factory="sftpSessionFactory"
expression="payload"
request-channel="toRm"
command="rm">
<int-sftp:request-handler-advice-chain>
<int:retry-advice />
</int-sftp:request-handler-advice-chain>
</int-sftp:outbound-gateway>
</beans>
Java-код
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath:/META-INF/spring-context.xml");
DownloadRemoteFileGateway downloadGateway = ctx.getBean(DownloadRemoteFileGateway.class);
DeleteRemoteFileGateway deleteGateway = ctx.getBean(DeleteRemoteFileGateway.class);
String downloadedFilePath = downloadGateway.downloadRemoteFile("si.sftp.sample/2ftptest");
System.out.println("downloadedFilePath: " + downloadedFilePath);
Boolean status = deleteGateway.deleteRemoteFile("si.sftp.sample/2ftptest");
System.out.println("deletion status: " + status);
Выше код работает как ожидалось. Он загружает удаленный файл, а затем удаляет его. У нас уже есть контрольная сумма загруженного файла с нами. Эта контрольная сумма вычисляется из удаленного файла. Можно ли построить механизм для вычисления контрольной суммы файла после его загрузки. Мы должны иметь возможность сравнивать ожидаемую контрольную сумму с контрольной суммой полученного файла и повторять фиксированное количество раз в случае несоответствия.
Мне интересно, могу ли я использовать RetryTemplate
как ниже. Это непроверенный псевдокод.
class Test {
@Autowired
DownloadRemoteFileGateway downloadGateway;
public void init() {
RetryTemplate template = new RetryTemplate();
ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(Long.parseLong(initialInterval));
backOffPolicy.setMaxInterval(Long.parseLong(initialInterval));
template.setRetryPolicy(new SimpleRetryPolicy(Integer.parseInt(maxAttempts), exceptionMap));
template.setBackOffPolicy(backOffPolicy);
}
void foo(){
Object result = template.execute(new RetryCallback() {
@Override
public String doWithRetry(RetryContext retryContext) throws Exception {
//Calculate received file checksum and compare with expected checksum
if(mismatch) {
downloadGateway.downloadRemoteFile(remoteFileName);
}
}, new RecoveryCallback() {
//same logic
});
}//foo
}//Test
Мой вопрос заключается в том, как заставить мой метод foo() выполняться после завершения загрузки файла. Также возможно получить загруженное имя файла в foo().
1 ответ
Я думаю, что то, что вам нужно, определенно можно сделать с помощью AOP Advices. Более того с цепочкой из них, где на самом деле RequestHandlerRetryAdvice
должен быть первым, чтобы начать повторную петлю. Следующий совет я бы предложил использовать как ExpressionEvaluatingRequestHandlerAdvice
с этими onSuccessExpression
а также propagateOnSuccessEvaluationFailures = true
сочетание. Таким образом, вы выполняете проверку контрольной суммы в onSuccessExpression
и если это не совпадает, бросить исключение. Это исключение будет поймано предыдущим в стеке RequestHandlerRetryAdvice
и логика повторения будет выполнена.
См. Их JavaDocs и Справочное руководство по этому вопросу.
Также у нас есть пример проекта, чтобы лучше понять вещи.