一般可以将数据库中的数据生成csv文件,对于多服务器部署的分布式微服务,有时候需要将生成的文件放在外部网关或其他服务器中

本篇可以实现通过代码连接其他服务器,并可以传送文件至其他服务器中,并且路径可以自定义
注:需要有另一台服务器的权限账号

连接另一台服务器的代码如下

/**
     * @param host 
     *            另一台服务器地址 
     * @param port 
     *            另一台服务器端口 
     * @param username 
     *            另一台服务器权限账户用户名 
     * @param password 
     *            另一台服务器权限账户密码 
     * @return 
     */
public ChannelSftp connect(String host, int port, String username,  String password) {  
            ChannelSftp sftp = null;   
            JSch jsch = new JSch();  
            jsch.getSession(username, host, port);  
            Session sshSession = jsch.getSession(username, host, port);   
            sshSession.setPassword(password); 
            Properties sshConfig = new Properties();  
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);  
            sshSession.connect();  
            Channel channel = sshSession.openChannel("sftp");  
            channel.connect();  
            sftp = (ChannelSftp) channel; 
            return sftp;  
    } 

将本地服务器上的文件传送至另一台服务器代码如下

/** 
     * 文件上传 
     *  
     * @param directory  上传至另一台服务器的存储路径
     * @param uploadFile 本服务器需要上传的文件路径及文件名
     * @param sftp  调用上方连接另一台服务器的方法connect
     */  
    public void SendFile(String directory, String uploadFile, ChannelSftp sftp) {  
        
        sftp.cd(directory);  
        File file = new File(uploadFile);  
        sftp.put(new FileInputStream(file), file.getName());  
        
    }

从另一台服务器上传送文件至本地服务器代码

/** 
     * 文件下载 
     *  
     * @param directory 另一台服务器的存储路径 
     * @param downloadFile 要下载的文件路径及文件名 
     * @param saveFile 下载下来的文件名(如下载到本地服务器需要更改文件名) 
     * @param sftp 调用上方连接另一台服务器的方法connect
     */  
    public void download(String directory, String downloadFile,  String saveFile, ChannelSftp sftp) {  
         
            sftp.cd(directory);  
            File file = new File(saveFile);  
            sftp.get(downloadFile, new FileOutputStream(file));  
         
    }  
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐