测试开发栈Java服务器端编程Java学习笔记

配置文件端到端同步方案

2017-03-07  本文已影响80人  测试开发栈

无论是项目开发还是分布式软件自动化测试,为了增加系统的灵活性和可配置性,我们常常使用在程序中读取本地配置的方式去控制系统,从而减少系统的停服和部署次数,这个过程是如何实现的呢?

一、方案逻辑
具体实现逻辑详见下图:


Paste_Image.png

二、具体实现
考虑到灵活性,下面代码还可以为SyncConfig创建一个构造方法SyncConfig (String lastModifiedPath),为变量remoteLastModifiedPath 赋值。

public class SyncConfig {
    private static String remoteLastModifiedPath = "\\\\remoteHost\\SharedFolder\\TestConfig\\lastModified";
    private static long lastModified = 0L;
    
    public static void syncConfig(String remotePath, String localPath){
        
        File sharedFile = new File(remotePath); 
        if(! sharedFile.exists() || ! sharedFile.isFile()){
            System.out.println("远端配置文件不存在");
            return;
        }
        
        lastModified = Long.parseLong(new DataConfig(remoteLastModifiedPath).readProperties("lastModified"));
        if(sharedFile.lastModified() <= lastModified){
            System.out.println("远端配置文件未更新,无需同步");
            return;
        }
        
        File localBackupFile = new File(localPath + ".bak");
        if(localBackupFile.exists()){
            localBackupFile.delete();
        }
        
        File localFile = new File(localPath);
        
        if(localFile.exists()){
            localFile.renameTo(localBackupFile);
            if(CommonUtil.copyFile(remotePath, localPath)){
                System.out.println("本地配置文件更新成功");
                new DataConfig(remoteLastModifiedPath).writeProperties("lastModified", String.valueOf(sharedFile.lastModified()));
            }else{
                localBackupFile.renameTo(new File(localPath));
                
                if(localFile.exists()){
                    System.out.println("本地配置文件还原成功");
                }else{
                    System.err.println("本地配置文件还原失败");
                }
            }
            
        }else{
            System.err.println("本地配置文件("+ localPath +")出现异常");
        }
    }
}

三、调用方式
在程序初始化时或者测试初始化时调用同步方法

    @BeforeSuite
    public void initSuite(){
        String sharedPath = "\\\\remoteHost\\SharedFolder\\TestConfig\\config.properties";
        String localPath = System.getProperty("user.dir") + "/testConfig/config.properties";
        SyncConfig.syncConfig(sharedPath, localPath);
    }     

四、改进方法
考虑到网络传输速度和配置文件大小的因素,建议调用同步方法的操作在子线程中进行,提升用户体验。

  new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            SyncConfig.syncConfig(sharedPath, localPath);           
        }
    }).start();

PS: 更多原创技术好文,请关注下方公众号:


code_share.jpg
上一篇 下一篇

猜你喜欢

热点阅读