如何将字节或流写入Apache Camel FTP以传输文件



在我目前的代码中,我从数据库中获取数据,然后用这些数据编写一个文件。我有这种骆驼路线和工作解决方案:-

private static final String INPUT_FILE_DIRECTORY_URI = "file:" + System.getProperty("user.home")
+ "/data/cdr/?noop=false";
private static final String SFTP_SERVER = "sftp://" +System.getProperty("user.name")
+ "@sftp_server_url/data/cdr/?privateKeyFile=~/.ssh/id_rsa&passiveMode=true";
from(INPUT_FILE_DIRECTORY_URI)
.streamCaching()
.log("Sending file to local sftp")
.to(SFTP_SERVER); 

我不想在本地磁盘中写入文件。相反,我想直接将文件数据写入SFTP服务器。我不知道怎么做?但我想这应该是可能的。你能告诉我这可能吗?如果是,怎么做?

我设法用另一种方式解决了这个问题。它更适合我的特定问题。

byte[] csvData = csvStringBuilder.toString().getBytes();
Routes.withProducer(producer)
.withHeader(Exchange.FILE_NAME, myCsvFile.csv)
.withBody(csvData)
.to(SFTP_SERVER).request(byte[].class);

除非你真的使用streamCaching,否则你不应该使用它。它将你的文件存储在内存中,如果你需要消耗数倍的输入,就使用它。

您可以使用Jpa组件或自定义bean来获取数据。从数据库加载它,然后将它发送到您的ftp服务器。

与Jpa:

@Entity 
@NamedQuery(name = "data", query = "select x from Data x where x.id = 1") 
public class Data { ... }

之后,您可以定义一个消费者uri,如下所示:

from("jpa://org.examples.Data?consumer.namedQuery=data")
.to("SFTP_SERVER");

编辑:将列表转换为csv并发送到ftp:

from("jpa://org.examples.Data?consumer.namedQuery=data")
.marshal()
.csv()
.to("sftp://" +System.getProperty("user.name") + 
"@sftp_server_url/data/cdr/myFile.csv?" +"privateKeyFile=~/.ssh/id_rsa&passiveMode=true");

请参阅将列表转换为CSV文件的CSV组件。

是的:(要做到这一点,请在camel DIRECT组件中发送文件inputStream,并在相关的路由中将其复制到FTP。在这种情况下,我使用from(directInputStreamName(.to(yourFtpUri(上传文件并直接将其复制到ftp。这是一个示例代码:

您的服务

@Service
public class FileService {
@Produce(uri = PfnumDownloadConstants.CAMEL_DIRECT_UPLOAD)
private ProducerTemplate producer;
public void sendFileToFtp(File fileToSend, String ftpDestinationUri) throws IOException {
Map<String, Object> headers = new HashMap<>();
//In this variable you can init the ftp destination uri or you can hard code it in route
headers.put("destinationUri", ftpDestinationUri);
//set filename to name your file in ftp
headers.put(Exchange.FILE_NAME_ONLY, file.getName());
InputStream targetStream = new FileInputStream(file);
//send stream as body and list of headers to direct 
producer.sendBodyAndHeaders(targetStream, headers);
}
}

您的骆驼路线

@Component
public class FileUploadRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
//Manage camel exception in a dedicated processor
onException(Exception.class).process(exceptionProcessor).log("error :: ${exception}");

from(CAMEL_DIRECT_UPLOAD)
.log("file copy to ftp '${header.CamelFileNameOnly}' in  process")
.toD("file:/mnt?fileName=${header.CamelFileNameOnly}&delete=false")
.log("copy done");
}
}

最新更新