转自:http://leign.iteye.com/blog/673407
数据分发还是同步
最近需要将一些文件从一台server备份到另一台server上(刷新新的数据到正式机上)
是根据刷新操作触发自动同步? 还是主动推(分发)过去?
想了想,觉得比较合理的解决还是看需要备份的数据量,如果是大规模的文件,为了提高效率,还是主动一点吧,推过去。 小批量文件,则还是可以被动同步。
用哪种方式
1、scp/sftp(SHH2)
可以使用http://www.ganymed.ethz.ch/ssh2/提供的jar包中的API,可以调用其接口进行基于SSH的连接,实现执行远程命令
Java代码
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import ch.ethz.ssh2.Connection;
- import ch.ethz.ssh2.SCPClient;
- import ch.ethz.ssh2.SFTPv3Client;
- import ch.ethz.ssh2.Session;
- import ch.ethz.ssh2.StreamGobbler;
- public class SCPTest {
- public static void main(String[] args)
- {
- String user = "root";
- String pass = "*****";
- String host = "remoteIP";
- Connection con = new Connection(host);
- try {
- con.connect();
- boolean isAuthed = con.authenticateWithPassword(user, pass);
- System.out.println("isAuthed===="+isAuthed);
- SCPClient scpClient = con.createSCPClient();
- scpClient.put("localFiles", "remoteDirectory"); //从本地复制文件到远程目录
- scpClient.get("remoteFiles","localDirectory"); //从远程获取文件
- SFTPv3Client sftpClient = new SFTPv3Client(con);
- sftpClient.mkdir("newRemoteDir", 6); //远程新建目录
- sftpClient.rmdir(""); //远程删除目录
- sftpClient.createFile("newRemoteFile"); //远程新建文件
- sftpClient.openFileRW("remoteFile"); //远程打开文件,可进行读写
- Session session = con.openSession();
- session.execCommand("uname -a && date && uptime && who"); //远程执行命令
- //显示执行命令后的信息
- System.out.println("Here is some information about the remote host:");
- InputStream stdout = new StreamGobbler(session.getStdout());
- BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
- while (true)
- {
- String line = br.readLine();
- if (line == null)
- break;
- System.out.println(line);
- }
- /* Show exit status, if available (otherwise "null") */
- System.out.println("ExitCode: " + session.getExitStatus());
- session.close();
- con.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
2、rsync
rsync是linux自带的备份文件/目录的软件,使用时需要配置一下需要同步的目录/认证之类的属性(/etc/rsyncd.conf),网上有太多的配置说明,就不多说了,但要找到一种适合自己应用且效率比较高的配置还是不容易。
3、sersync
sersync主要用于服务器同步,web镜像等功能。基于boost1.41.0,inotify api,rsync command.开发。目前使用的比较多的同步解决方案是inotify-tools+rsync ,另外一个是google开源项目Openduckbill(依赖于inotify- tools),这两个都是基于脚本语言编写的。相比较上面两个项目,本项目优点是: sersync是使用c++编写,而且对linux系统文件系统产生的临时文件和重复的文件操作进行过滤(详细见附录,这个过滤脚本程序没有实现),所以在结合rsync同步的时候,节省了运行时耗和网络资源。因此更快。
相比较上面两个项目,sersync配置起来很简单,其中bin目录下已经有基本上静态编译的2进制文件,配合bin目录下的xml配置文件直接使用即可。
另外本项目相比较其他脚本开源项目,使用多线程进行同步,尤其在同步较大文件时,能够保证多个服务器实时保持同步状态。
本项目有出错处理机制,通过失败队列对出错的文件重新同步,如果仍旧失败,则每10个小时对同步失败的文件重新同步。
本项目自带crontab功能,只需在xml配置文件中开启,即可按您的要求,隔一段时间整体同步一次。无需再额外配置crontab功能。
本项目socket与http插件扩展,满足您二次开发的需要。
安装和配置也见http://code.google.com/p/sersync/
上面是其简介和特点,其配置是基于rsync的,配置sersync之前需要启动rsync的守护进程,然后配置confxml.xml文件,类似于rsync的/etc/rsyncd.conf,主要是配置目的server的地址、目录以及本地目录。
我们可以根据情况选择方式1进行主动分发,或者选择方式2或3进行同步。
数据分发/同步