日期:2014-05-16 浏览次数:20919 次
产品化的系统免不了要实现的就是系统的自动更新,下边讲讲我在工作中实现的win下的产品自动更新。
自动更新步骤:
1、本地系统版本与服务器最新版本比对。
2、发现更新版本后进行升级版下载。
3、关闭应用服务器,更新本地程序,清除缓存,执行sql脚本,重启应用服务器
其中1、2步我是使用java实现的,使用了HttpClient来与服务器端(这里是相对应终端客户来说,指的是产品提供商的运营平台)进行交互,发现更新版本后下载到终端客户本地第3部是借用bat命令来实现的,关闭tomcat,解压下载包,清空tomcat缓存文件夹work,执行sql脚本,重启应用并提醒维平台更新完成。
?
如下代码为进行版本比对并下载服务器端更新文件
?
public class VersionUpdate {
protected int connectTimeout = 30 * 1000; // 连接超时:30s
protected int readTimeout = 1 * 1000 * 1000; // IO超时:1min
//标识,是否存在新的更新文件
private boolean isUpdated = false;
//当前系统版本
private String localVerStr ;
//保存最新的版本
String netVersion;
public void update() {
SystemManager manager = (SystemManager)BeanFactoryProxy.getBean("systemManager");
Register register = manager.getRegister();
localVerStr = this.getNowVer(StringUtils.replaceAll(register.getPhysicalPath(), '\\', '/')+"/webapps/quickLMS/WEB-INF/classes/ver.txt");
/*
这里是通过HTTP访问一个页面,以取得网络上的版本号
比如这里就是在这个页面直接打印出 6.19.1.1
然后把这个版本号比对本地的版本号,如果版本号不同的话,就从网络上下载新的程序并覆盖现有程序
*/
//读取网络上的版本号
try {
netVersion = HttpPostUtil.doGet(ConstLMS.NEW_VERSION);
if (netVersion.equals(localVerStr)) {
System.out.println("当前文件是最新版本");
isUpdated = false;
} else {
System.out.println("存在更新文件,现在开始更新");
isUpdated = true;
}
}catch (Exception ex) {
ex.printStackTrace();
}
//如果版本不同,下载网络上的文件,更新本地文件
if (isUpdated) {
//缓存网络上下载的文件
File newFile = new File(register.getPhysicalPath()+"/webapps/" + StringUtils.DateToStr(new Date(), "yyyyMMdd")+".zip");
//获取网络上的文件位置
String netFileAddress = ConstLMS.MNG_ADDRESS+HttpPostUtil.doGet(ConstLMS.NEW_VERSION_ADDRESSS+"&sn="+register.getSn());
FileOutputStream fos = null;
BufferedInputStream bis = null;
try {
//打开URL通道
URL url = new URL(netFileAddress);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
conn.connect();
bis = new BufferedInputStream(conn.getInputStream());
byte[] buffer = new byte[1024];
int size = 0;
fos = new FileOutputStream(newFile);
System.out.println("正在从网络上下载新的更新文件");
//保存文件
try {
while ((size = bis.read(buffer)) != -1) {
fos.write(buffer, 0, size);
fos.flush();
}
} catch (Exception ex4) {
System.out.println(ex4.getMessage());
}
System.out.println("文件下载完成");
} catch (Exception ex) {
System.out.println("文件读取错误");
} finally {
try{
if(bis!=null){
bis.close();
}
}catch(Exception exp){
exp.printStackTrace();
}
try {
if(fos!=null){
fos.close();
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
batExec(register.getPhysicalPath());
}
}
private String getNowVer(String nowVersionURL) {
//本地版本文件
File verFile = new File(nowVersionURL);
FileReader is = null;
BufferedReader br = null;
//读取本地版本
try {
is = new FileReader(verFile);
br = new BufferedReader(is);
String ver = br.readLine();
return ver;
} catch (FileNotFoundException ex) {
System.out.println("本地版本文件未找到");