通过翻找网上资料,目前主流有三种方案
1.SSH、SCP
2.FTP
3.文件服务器
因为文件同步不是项目的核心流程,所以这里为了简便实用ganymed实现文件数据同步。
依赖:
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionInfo;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
@Slf4j
public class ClusterFilesSync extends Thread{
private static final String remoteUser = "xxx";
private static final String remotePass = "xxx";
//此处为服务器scp时的解密算法,可忽略
#private static String[] ciphers = {"3des-cbc"};
private String absFileName = "";
private String folderName = "";
private String method = "";
public ClusterFilesSync(String absFileName,String folderName,String method) {
this.absFileName = absFileName;
this.folderName = folderName;
this.method = method;
}
@Override
public void run() {
try {
ArrayList<String> al = getHosts();
for(String s:al){
//循环同步每台服务器上的文件
sync(s,22,folderName,absFileName,method);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取需要同步的服务器列表
* @return
*/
public static ArrayList<String> getHosts(){
String[] ips = {"xxx","xxx"};
ArrayList<String> al = new ArrayList<String>();
for(String s:ips){
al.add(s);
}
String localIp = "";
try {
//获取当前操作的服务器的IP地址,linux的etc/hosts中要配置好网络地址,不然只会得到127.0.0.1
// localIp = InetAddress.getLocalHost().getHostAddress();
//因有多个网卡地址,通过host直接配置获取想要的地址IP
localIp = InetAddress.getByName("intranet").getHostAddress();
log.info("本机IP地址为:{}"+localIp);
} catch (UnknownHostException e) {
e.printStackTrace();
}
al.remove(localIp);
return al;
}
/**
* 简单的文件同步
* @return
*/
public static void sync(String ip,int port,String folderName,String absFileName,String method){
String path = "/data/index-system/uploadFile/"+folderName;
Connection con = new Connection(ip, port);
String cmd = "";
//连接
try {
//上传方案
if("upload".equals(method)) {
con.setClient2ServerCiphers(ciphers);
con.setServer2ClientCiphers(ciphers);
ConnectionInfo connect = con.connect();
//远程服务器的用户名密码
boolean isAuthed = con.authenticateWithPassword(remoteUser, remotePass);
Session session = con.openSession();
cmd = "mkdir folderName";
session.execCommand(cmd);
//建立SCP客户端
if (isAuthed) {
SCPClient scpClient = con.createSCPClient();
//将文件同步到指定的path目录下面
scpClient.put(path+"/"+absFileName, path);
log.info("文件同步成功");
} else {
log.error("文件同步失败");
}
session.close();
con.close();
} else if ("delete".equals(method)){
con.connect();
boolean isAuthed = con.authenticateWithPassword(remoteUser, remotePass);
Session session = con.openSession();
cmd = "rm -rf folderName";
session.execCommand(cmd);
log.info("文件删除成功:{}",folderName);
session.close();;
con.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}