实现异构系统的数据非实时同步 接口

     写了个接口,核心思想是两个异构系统之间实现数据的非实时同步。  也就是说平台1生成的数据在每天规定时间放到FTP服务器地址中去,平台2在规定的时间去取数据。这样就可以实现了非实时数据同步。  思想虽说不难理解,但是实现起来还是费了很多功夫。其中涉及的到的技术就有FTP 协议、定时器原理、服务器集群分布思想、ServletContextListener原理。 本代码已经对接成功 ,现分享代码如下,在此抛砖引玉------(相关jar包就不提供了,网上都有)


具体代码如下:

1.监听器类

package com.usermsgsync.servlet;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.usermsgsync.time.TimerManagerDay;
import com.usermsgsync.time.TimerManagerMon;


/**
 * @see 用于监听WEB 应用启动和销毁的事件,监听器类需要实现ServletContextListener接口
 * @author 
 *
 */
public class ContextListener implements ServletContextListener 
{
    
	//获取容器中的ServletContext(上下文),为了取到配置中的键值
	public void contextInitialized(ServletContextEvent event) 
	{
		//定时器管理方法,以构造方法获取<context-param>中的键值
		new TimerManagerDay(event.getServletContext());
		new TimerManagerMon(event.getServletContext());
	}
	
	//在服务器停止运行的时候停止所有的定时任务
	public void contextDestroyed(ServletContextEvent event)
	{
	
	}
}


2.处理具体业务类

package com.usermsgsync;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.entity.Userreg;
import com.usermsgsync.time.DateUtil;
import com.userreg.dao.UserRegDao;



public class UserSyncMsg 
{

	private static UserRegDao userDao = UserRegDao.getInstance();
	
	private static final String VersionNo = UserSyncMsgConfig.getValue("userSyncMsg_VersionNo");        //版本信息,4位,采用VXXX格式,本版本填V010
	private static final String PlatformID = UserSyncMsgConfig.getValue("userSyncMsg_PlatformID");      //XXX平台分配给XX共享平台的编号,6位
	private static final String InterfaceNo = UserSyncMsgConfig.getValue("userSyncMsg_InterfaceNo");    //同步接口编号,两位。(01: 用户状态信息通知接口)

	private static String createDate;      //文件产生日期,14位。格式为YYYYMMDDHHMMSS 
	private static String day = "Day";   //文件标示   Day表示增量文件
	private static String mon = "Mon";   //文件标示   Mon表示按月的全量文件
	
	//服务器端的:每日/月源文件的保存目录  
	private static String userMsgfileDir = "//home//stemp//ROOT//fileDir//"; 
	
	
//	本地调试用的
//	private static String userMsgfileDir = "F:\\" + VersionNo + "\\" + InterfaceNo + "\\" + PlatformID ;  //请求文件目录:每日/月源文件的保存目录  
//	private static String ReturnDir  = RequestDir + "\\RSP";   //回执文件目录
	
	
	
	/**
	 * 生成每天的增量同步源文件,并远程上传到FTP服务器
	 */
	public static void createFileDay() 
	{
		
		//判断目录是否存在 不存在创建
		directoryExists(userMsgfileDir);
		
         //获取前一天的增量内容
		List<Userreg> list = getUserListDay();
		String fileContent = getFileContent(list);
		
		//日期格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDDHHmmss");
		// 请求文件名:
		createDate = sdf.format(new Date());
		String fileName = InterfaceNo + PlatformID + createDate + "_" + day;
		
		String requestFileName = fileName + ".txt"; //请求文件名
		System.out.println("--请求文件名---->"+requestFileName);
		
		// 生成每天增量请求文件,并将内容写入文件
		File file = new File(userMsgfileDir, requestFileName);
		createFile(file, fileContent);
		uploadFile(requestFileName);
	}
		

	/**
	 * 生成每月的全量的同步文件
	 */
	public static void createFileMon() 
	{
//		System.out.println("--请求文件目录(每月的)---->"+userMsgfileDir);
		//判断目录是否存在 不存在创建
		directoryExists(userMsgfileDir);
		
               //获取全量内容
		List<Userreg> list = getUserListAll(); 
		String fileContent = getFileContent(list);
		
		//日期格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDDHHmmss");
		//请求文件名:
		createDate = sdf.format(new Date());
		String fileName = InterfaceNo + PlatformID + createDate + "_" + mon;
		String requestFileName = fileName + ".txt";
		
		// 生成请求文件,并将内容写入文件
		File file = new File(userMsgfileDir, requestFileName);
		createFile(file, fileContent);
	}
		
	
	/**
	 * 得到每日的增量信息(注意:由于此处的定时器的优先级太高,还没有完全启动完就已经执行了,所以取不到数据)
	 */
	public static List<Userreg> getUserListDay() 
	{
		// 得到当前时间 的前一天
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = DateUtil.getSpecifiedDayBefore(sdf.format(new Date()));
		// 获取前一天的增量
		String hql = "from Userreg u where u.regtime BETWEEN '"+date+" 00:00:00' AND '"+date+" 24:00:00'";
//		String sql = "select *from userreg where bak2 between '"+date+" 00:00:00' and '"+date+" 24:00:00'";
		
		System.out.println("--进入查询每日增量---->"+hql);
		return userDao.getUserList(hql);
	}
	
	
	/**
	 * 每月一次的全量信息
	 */
	public static List<Userreg> getUserListAll() 
	{
		Date nowDate = new Date() ;
		String firstDay = DateUtil.getFirstDayOfMonth(nowDate);
		String lastDay = DateUtil.getLastDayOfMonth(nowDate);
		
		String hql = "from Userreg u where u.regtime BETWEEN '"+firstDay+" 00:00:00' AND '"+lastDay+" 24:00:00'";
		
		return userDao.getUserList(hql);
	}


	/**
	 * 文件内容格式
	 * @param list
	 * @return
	 */
	private static String getFileContent(List<Userreg> list) 
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) 
		{
			sb.append(list.get(i).getUserphone() + "," + list.get(i).getEmail()+ "," + list.get(i).getUserstate());
			sb.append("\r\n");
		}
		System.out.println("--获取文件内容格式---->"+sb.toString());
		return sb.toString();
	}


	/**
	 * 判断目录是否存在,如果不存在,则创建
	 * @param dir
	 */
	private static void directoryExists(String dir) 
	{
		// 保存目录
		File saveDirectory = new File(dir);
		// 如果不存在则创建多级目录
		if (!saveDirectory.exists()) 
		{
			saveDirectory.mkdirs();
		}
	}
	
	
	/**
	 * 创建文件 并将内容写入文件
	 * @param file
	 * @param content
	 */
	private static void createFile(File file, String content) 
	{
		try 
		{
			if (file.exists()) 
			{
				file.delete();
				file.createNewFile();
				// 将内容写入文件
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
				bos.write(content.getBytes());
				bos.flush();
				bos.close();
			} 
			else 
			{
				System.out.println("--写入文件内容方法---->");
				file.createNewFile();
				// 将内容写入文件
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
				bos.write(content.getBytes());
				bos.flush();
				bos.close();
			}
		}
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 远程上传文件到FTP服务器
	 * @param requestFileName
	 */
	private static void uploadFile(String requestFileName)
	{
		String ip =  UserSyncMsgConst.IP ;
		int port  =  UserSyncMsgConst.Port ; 
		String user =UserSyncMsgConst.User ;  
		String pwd = UserSyncMsgConst.Pwd ;  
		String requestDir = UserSyncMsgConst.RequestDir ;
		System.out.println("----ftp请求文件目录--->"+ requestDir);
		
		
		List<File> fileList = new ArrayList<File>();
		File onefile = new File(userMsgfileDir,requestFileName); 	
		System.out.println("----服务器端的文件路径--->"+ onefile.getAbsolutePath());
		fileList.add(onefile);
		
		FTPUtil ftpupload = new FTPUtil(ip,port,user,pwd);
		try 
		{
			ftpupload.uploadFile(requestDir, fileList);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 远程删除FTP服务器下的请求文件目录
	 */
	public static void deleteFilesDay()
	{
		String ip =  UserSyncMsgConst.IP ; //第1台FTP服务器
		int port  =  UserSyncMsgConst.Port ; 
		String user =UserSyncMsgConst.User ;  
		String pwd = UserSyncMsgConst.Pwd ;  
		String requestDir = UserSyncMsgConst.RequestDir ;
		
//		String ip1 =  UserSyncMsgConst.IP1 ; //第2台FTP服务器
		
		FTPUtil ftpupload = new FTPUtil(ip,port,user,pwd);
//		FTPUtil ftpupload1 = new FTPUtil(ip1,port,user,pwd);
		try 
		{
			ftpupload.deleteAllFile(requestDir);
//			ftpupload1.deleteAllFile(remotePath);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
}


3. 常量类,其实可以去掉,因为已经有了properties文件

package com.usermsgsync;

/**
 * 配置用户同步信息常量
 * @author 
 *
 */
public class UserSyncMsgConst 
{
	public static final String IP = UserSyncMsgConfig.getValue("userSyncMsg_FTP_IP") ;                      //FTP服务器的ip
	public static final int Port = Integer.parseInt(UserSyncMsgConfig.getValue("userSyncMsg_FTP_port"));    //FTP服务器的端口
	public static final String User = UserSyncMsgConfig.getValue("userSyncMsg_FTP_userName");               //FTP服务器的用户名
	public static final String Pwd = UserSyncMsgConfig.getValue("userSyncMsg_FTP_passWord") ;               //FTP服务器的密码
	
	
	public static final String RequestDir =UserSyncMsgConfig.getValue("userSyncMsg_FTP_RequestDir") ;         //FTP服务器的配置的上传目录(请求文件目录)
	
}


4. 读取配置文件方法

package com.usermsgsync;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import com.weibo.weibo4j.util.URLEncodeUtils;

@SuppressWarnings("static-access") 
public class UserSyncMsgConfig
{
    
    private static String filePath = UserSyncMsgConfig.class.getResource("/").getPath() + "userSyncMsgConfig.properties";

    public UserSyncMsgConfig()
    {
    }

    private static Properties props = new Properties();
    static
    {
        try
        {
            String filePaths = new URLEncodeUtils().decodeURL(filePath);
            System.out.println(filePaths);
            props.load(new FileInputStream(filePaths));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static String getValue(String key)
    {
        return props.getProperty(key);
    }

    public static void updateProperties(String key, String value)
    {
        props.setProperty(key, value);
    }

}


5.远程FTP处理类

package com.usermsgsync;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
//import org.apache.commons.net.ftp.FTPClientConfig; 
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/** 远程FTP处理类
 * 
 * @author suchiheng
 * @version 1.0, 2012/09/15 */
public class FTPUtil
{

    private Logger logger = Logger.getLogger(FTPUtil.class);
    private String ip;
    private int port;
    private String pwd;
    private String user;
    private FTPClient ftpClient;

    private FTPUtil()
    {
    }

    public FTPUtil(String ip, int port, String user, String pwd)
    {

        this.ip = ip;
        this.port = port;
        this.user = user;
        this.pwd = pwd;
    }

    /** 连接远程FTP服务器
     * 
     * @param ip
     *            地址
     * @param port
     *            端口号
     * @param user
     *            用户名
     * @param pwd
     *            密码
     * @return
     * @throws Exception */
    public boolean connectServer(String ip, int port, String user, String pwd) throws Exception
    {

        boolean isSuccess = false;
        try
        {
            ftpClient = new FTPClient();
            ftpClient.connect(ip, port);
            ftpClient.setControlEncoding("GBK");
//    		FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); //此类commons-net-2.0不提供
//    		conf.setServerLanguageCode("zh");
            ftpClient.login(user, pwd);
            ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
            {
                isSuccess = true;
                System.out.println("--连接ftp服务器成功!!!");
            }
            else
            {
                ftpClient.disconnect();
                logger.error("连不上ftp服务器!");
//				throw new BossOperException();
            }
        }
        catch (Exception e)
        {
            logger.error("连接FTP服务器异常..", e);
            e.printStackTrace();
        }

        return isSuccess;
    }

    /** 远程FTP上传文件
     * 
     * @param remotePath
     * @param localPath
     * @param files
     * @return
     * @throws Exception */
    public File uploadFile(String remotePath, List<File> files) throws Exception
    {
        File fileIn = null;
        OutputStream os = null;
        FileInputStream is = null;
        try
        {
            for (File file : files)
            {
                if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
                {
                    System.out.println("----进入文件上传到FTP服务器--->");
                    ftpClient.changeWorkingDirectory(remotePath);
                    os = ftpClient.storeFileStream(file.getName());
                    fileIn = file;
                    is = new FileInputStream(fileIn);
                    byte[] bytes = new byte[1024];
                    int c;
                    while ((c = is.read(bytes)) != -1)
                    {
                        os.write(bytes, 0, c);
                    }
                }
            }
        }
        catch (Exception e)
        {
            logger.error("上传FTP文件异常: ", e);
        }
        finally
        {
            os.close();
            is.close();
            ftpClient.logout();
            if (ftpClient.isConnected())
            {
                ftpClient.disconnect();
            }
        }

        return fileIn;
    }

    /** 远程FTP上删除一个文件
     * 
     * @param remotefilename
     * @return */
    public boolean deleteFile(String remotefilename)
    {
        boolean flag = true;
        try
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
            {
                flag = ftpClient.deleteFile(remotefilename);
                if (flag)
                {
                    System.out.println("远程删除FTP文件成功!");
                }
                else
                {
                    System.out.println("-----远程删除FTP文件失败!----");
                }
            }
        }
        catch (Exception ex)
        {
            logger.error("远程删除FTP文件异常: ", ex);
            ex.printStackTrace();
        }
        return flag;
    }

    /** 远程FTP删除目录下的所有文件
     * 
     * @param remotePath
     * @return
     * @throws Exception */
    public void deleteAllFile(String remotePath) throws Exception
    {
        try
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
            {
                ftpClient.changeWorkingDirectory(remotePath);
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile file : ftpFiles)
                {
                    System.out.println("----删除远程FTP服务器文件--->" + file.getName());
                    ftpClient.deleteFile(file.getName());

                }
            }
        }
        catch (Exception e)
        {
            logger.error("从FTP服务器删除文件异常:", e);
            e.printStackTrace();
        }
        finally
        {
            ftpClient.logout();
            if (ftpClient.isConnected())
            {
                ftpClient.disconnect();
            }
        }
    }

    /** 远程FTP上创建目录
     * 
     * @param dir
     * @return */
    public boolean makeDirectory(String dir)
    {
        boolean flag = true;
        try
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
            {
                flag = ftpClient.makeDirectory(dir);
                if (flag)
                {
                    System.out.println("make Directory " + dir + " succeed");
                }
                else
                {
                    System.out.println("make Directory " + dir + " false");
                }
            }
        }
        catch (Exception ex)
        {
            logger.error("远程FTP生成目录异常:", ex);
            ex.printStackTrace();
        }
        return flag;
    }

    /** 远程FTP下载文件
     * 
     * @param remotePath
     * @param localPath
     * @return
     * @throws Exception */
    public List<File> downloadFile(String remotePath, String localPath) throws Exception
    {
        List<File> result = new ArrayList<File>();
        File fileOut = null;
        InputStream is = null;
        FileOutputStream os = null;
        try
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
            {
                ftpClient.changeWorkingDirectory(remotePath);
                FTPFile[] ftpFiles = ftpClient.listFiles();

                for (FTPFile file : ftpFiles)
                {
                    is = ftpClient.retrieveFileStream(file.getName());
                    if (localPath != null && !localPath.endsWith(File.separator))
                    {
                        localPath = localPath + File.separator;
                        File path = new File(localPath);
                        if (!path.exists())
                        {
                            path.mkdirs();
                        }
                    }
                    fileOut = new File(localPath + file.getName());
                    os = new FileOutputStream(fileOut);
                    byte[] bytes = new byte[1024];
                    int c;
                    while ((c = is.read(bytes)) != -1)
                    {
                        os.write(bytes, 0, c);
                    }

                    result.add(fileOut);
                    ftpClient.completePendingCommand();
                    os.flush();
                    is.close();
                    os.close();
                }

                for (FTPFile file : ftpFiles)
                {
                    ftpClient.deleteFile(file.getName());
                }
            }
        }
        catch (Exception e)
        {
            logger.error("从FTP服务器下载文件异常:", e);
            e.printStackTrace();
        }
        finally
        {
            ftpClient.logout();
            if (ftpClient.isConnected())
            {
                ftpClient.disconnect();
            }
        }

        return result;
    }

    public String getIp()
    {
        return ip;
    }

    public void setIp(String ip)
    {
        this.ip = ip;
    }

    public int getPort()
    {
        return port;
    }

    public void setPort(int port)
    {
        this.port = port;
    }

    public String getPwd()
    {
        return pwd;
    }

    public void setPwd(String pwd)
    {
        this.pwd = pwd;
    }

    public String getUser()
    {
        return user;
    }

    public void setUser(String user)
    {
        this.user = user;
    }

    /** 测试方法
     * 
     * @param args */
    public static void main(String[] args)
    {
        String ip = UserSyncMsgConst.IP;
        int port = UserSyncMsgConst.Port;
        String user = UserSyncMsgConst.User;
        String pwd = UserSyncMsgConst.Pwd;
        String requestDir = UserSyncMsgConst.RequestDir;

        // 上传文件配置
//		List<File> fileList = new ArrayList<File>();
		File onefile = new File("F:\\V010\\01\\000011\\RSP\\0100001120120701122712_Day.txt");
//		File onefile = new File("F:\\V010\\01\\000011\\RSP\\" ,"01000011201209263112839_Day.txt");
//		System.out.println("----本地文件路径--->"+ onefile.getAbsolutePath());
//		fileList.add(onefile);

        FTPUtil ftpupload = new FTPUtil(ip, port, user, pwd);
        try
        {
//			ftpupload.uploadFile(remotePath, fileList);  //测试上传文件

            // 删除文件
//			String remotefilename = remotePath+"01000011201209263112839_Day.txt";
//			System.out.println("----远程FTF上的文件名----"+remotefilename);
//			ftpupload.deleteFile(remotefilename);

            // 删除目录下所有的文件
//			ftpupload.deleteAllFile(RequestDir);

            // 下载目录下所有的文件
//			String localPath = "F:\\TEST\\" ;
//			ftpupload.downloadFile(remotePath, localPath);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}


6. 相关时间处理类和定时器类

package com.usermsgsync.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;



/**
 * 相关时间处理类
 * @author suchiheng
 * @version 1.0,  2012/09/15
 */
public class DateUtil 
{
	/**
	 * 获得指定日期的前一天
	 * 
	 * @param specifiedDay
	 * @return
	 * @throws Exception
	 */
	public static String getSpecifiedDayBefore(String specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		Date date = null;
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		try 
		{
			
			date = simpleDateFormat.parse(specifiedDay);
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - 1);

		String dayBefore = simpleDateFormat.format(c.getTime());
		return dayBefore;
	}

	/**
	 * 获得指定日期的后一天
	 * 
	 * @param specifiedDay
	 * @return
	 */
	public static String getSpecifiedDayAfter(String specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		Date date = null;
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		try 
		{
			date = simpleDateFormat.parse(specifiedDay);
		}
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day + 1);

		String dayAfter = simpleDateFormat.format(c.getTime());
		return dayAfter;
	}
	
	/**
	 * 获取指定时间的上个月的最后一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getLastDayOfMonth(String specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try 
		{
			date = simpleDateFormat.parse(specifiedDay); //转化为Date格式
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		c.setTime(date);
		
		c.add(Calendar.MONTH, -1); //获取上一个月
		
		int maxDate = c.getActualMaximum(Calendar.DAY_OF_MONTH);
	    c.set(Calendar.DAY_OF_MONTH, maxDate);
		
		String LastDayOfMonth = simpleDateFormat.format(c.getTime()); //格式化时间格式
		return LastDayOfMonth;
	}
	
	
	/**
	 * 获取指定时间的上个月的最后一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getLastDayOfMonth(Date specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		c.setTime(specifiedDay);
		c.add(Calendar.MONTH, -1); //设置上一个月
		
		int maxDate = c.getActualMaximum(Calendar.DAY_OF_MONTH); //设置最后一天
	    c.set(Calendar.DAY_OF_MONTH, maxDate);
		
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		String LastDayOfMonth = simpleDateFormat.format(c.getTime());   //格式化时间格式
		return LastDayOfMonth;
	}
	
	/**
	 * 获取指定时间的上个月的第一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getFirstDayOfMonth(String specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try 
		{
			date = simpleDateFormat.parse(specifiedDay); //转化为Date格式
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		c.setTime(date);
		c.add(Calendar.MONTH, -1); //设置上一个月
		
		int MiniDate = c.getActualMinimum(Calendar.DAY_OF_MONTH);
	    c.set(Calendar.DAY_OF_MONTH, MiniDate);
		
		String FirstDayOfMonth = simpleDateFormat.format(c.getTime());
		return FirstDayOfMonth ;
	}
	
	/**
	 * 获取上个月的第一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getFirstDayOfMonth(Date specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");

		c.setTime(specifiedDay);
		
		c.add(Calendar.MONTH, -1); //设置上一个月
		
		int MiniDate = c.getActualMinimum(Calendar.DAY_OF_MONTH);
	    c.set(Calendar.DAY_OF_MONTH, MiniDate);
		
		String FirstDayOfMonth = simpleDateFormat.format(c.getTime());
		return FirstDayOfMonth ;
	}
	
	
	
	/**
	 *  
	 * 方法描述:取得当前日期的上月或下月日期 ,amount=-1为上月日期,amount=1为下月日期;创建人:
	 * @param s_DateStr
	 * @param s_FormatStr
	 * @return
	 * @throws Exception
	 */
	public static String getFrontBackStrDate(String strDate,int amount) throws Exception 
	{
		if (null == strDate) 
		{
			return null;
		}
		try 
		{

			SimpleDateFormat fmt = new SimpleDateFormat("yy-MM-dd");
			Calendar c = Calendar.getInstance();
			c.setTime(fmt.parse(strDate));
			c.add(Calendar.MONTH, amount);
			return fmt.format(c.getTime());
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return "";
	}

	
	/**
	 * 返回两时间差,拼接成字符串返回
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static String getTimeSub(Long time1, Long time2 )
	{
		String result = "";
		try 
		{
			Long diff = time2 - time1;   //两时间差,精确到毫秒 
			
			Long day = diff / (1000 * 60 * 60 * 24);         //以天数为单位取整
			Long hour=(diff/(60*60*1000)-day*24);            //以小时为单位取整 
			Long min=((diff/(60*1000))-day*24*60-hour*60);        //以分钟为单位取整 
			Long secone=(diff/1000-day*24*60*60-hour*60*60-min*60);
			
			result = day + "|" + hour+ "|" + min ; 
			System.out.println("---两时间差---> " +day+"天"+hour+"小时"+min+"分"+secone+"秒");
	
		} 
		catch (RuntimeException e) 
		{
			e.printStackTrace();
		}
		return result ;
	}
	
	
}


7. 定时器

package com.usermsgsync.time;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContext;

public class TimerManagerDay
{

    // 时间间隔 一天
    private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
    // 调试时间(1分)
//	private static final long PERIOD_DAY = 60 * 1000;
    private ServletContext servletContext = null;

    public TimerManagerDay(ServletContext context)
    {
        this.servletContext = context;
        // 获取配置中的时间信息
        String hour = this.servletContext.getInitParameter("hour");
        String minute = this.servletContext.getInitParameter("minute");

        Calendar calendar = Calendar.getInstance();

        // 定制每日00:00点执行方法
        calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour));
        calendar.set(Calendar.MINUTE, Integer.valueOf(minute));

        // 第一次执行定时任务的时间
        Date date = calendar.getTime();

        // 如果第一次执行任务的时间小于当前时间 ,此时要在第一次任务的时间上加上一天,如果不加上一天 ,任务会立即执行
        if (date.before(new Date()))
        {
            date = this.addDay(date, 1);
        }

        Timer time = new Timer();
        // 安排指定的任务 在指定的时间 执行
        UserMsgTimerTask dataTask = new UserMsgTimerTask();
        time.schedule(dataTask, date, PERIOD_DAY);

    }

    /** 给时间加任意一天
     * 
     * @param date
     * @param num
     * @return */
    public Date addDay(Date date, int num)
    {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, 1); // 加一天
        return startDT.getTime();
    }

}


package com.usermsgsync.time;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContext;

public class TimerManagerMon 
{

	private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;  //因为每月第一天不是固定的频率,所以设置为每天某个时间
	private ServletContext servletContext = null;

	public TimerManagerMon(ServletContext context)
	{
		this.servletContext = context;
		// 获取配置中的时间信息
		String hour = this.servletContext.getInitParameter("hour");
		String minute = this.servletContext.getInitParameter("minute");

		// 安排指定的任务 在指定的时间 执行
		UserMsgTimerTask2 dataTask = new UserMsgTimerTask2();

		// 判断时间
		Date d = new Date();// 获取服务器的时间。。。
		Calendar c = Calendar.getInstance();
		Timer timer = new Timer();
		c.setTime(d);

		//设置定时器的启动时间
		if (c.get(Calendar.DAY_OF_MONTH) == 1) // 当前是1号
		{
			if (c.get(Calendar.HOUR_OF_DAY) == 0 && c.get(Calendar.MINUTE) == 0) 
			{
				timer.scheduleAtFixedRate(dataTask, c.getTime(), PERIOD_DAY); // 每天执行一次run()方法...
			} 
			else 
			{
				// 下月一号开始
				c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 1);    // 设置为下月
				c.set(Calendar.DAY_OF_MONTH, 1);					 // 设置为下月的1号
				c.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour));  //定制每日00:00点执行方法
				c.set(Calendar.MINUTE, Integer.valueOf(minute));
				timer.scheduleAtFixedRate(dataTask, c.getTime(), PERIOD_DAY); // 每天执行一次run()方法...
			}
		} 
		else // 当前不是1号 则从下个月1号开始执行定期任务
		{
			c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 1);     // 设置为下月
			c.set(Calendar.DAY_OF_MONTH, 1);					  // 设置为下月的1号
			c.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour));   //定制每日00:00点执行方法
			c.set(Calendar.MINUTE, Integer.valueOf(minute));
			timer.scheduleAtFixedRate(dataTask, c.getTime(), PERIOD_DAY); // 每天执行一次run()方法...
		}
	}
}



package com.usermsgsync.time;

import java.util.TimerTask;

import com.usermsgsync.UserSyncMsg;

public class UserMsgTimerTask extends TimerTask 
{
	
	@Override
	public void run() 
	{
		try 
		{
			UserSyncMsg.deleteFilesDay(); //此方法必须放在生成当天文件前面,因为获取java代码获取服务器时间并不能保证每次都能生成的是一模一样的值
			UserSyncMsg.createFileDay();
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
		}
	}

}




package com.usermsgsync.time;

import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;

import com.usermsgsync.UserSyncMsg;

public class UserMsgTimerTask2 extends TimerTask 
{

	@Override
	public void run() 
	{
		try 
		{
			//在方法内部判断是否为每月的第一天
			Date date = new Date(); //获取服务器的时间
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			if (calendar.get(Calendar.DAY_OF_MONTH) == 1 )
			{
				UserSyncMsg.createFileMon();		
			}
		}
		catch (Exception e) 
		{
			// TODO: handle exception
		}
	}

}


8.  在web.xml中的配置

<!--生成增量同步文件监听器 -->
	<listener>
		<listener-class>
			com.usermsgsync.servlet.ContextListener
		</listener-class>
	</listener>
	<!--一天一次增量同步 时间设置 -->
	<context-param>
		<param-name>hour</param-name>
		<param-value>0</param-value>
	</context-param>
	<context-param>
		<param-name>minute</param-name>
		<param-value>0</param-value>
	</context-param>


9. properties文件

userSyncMsg_VersionNo = V010
userSyncMsg_PlatformID = 000011
userSyncMsg_InterfaceNo = 01

userSyncMsg_FTP_IP = 211.94.123.188
userSyncMsg_FTP_port = 21
userSyncMsg_FTP_userName = Beau Virgill
userSyncMsg_FTP_passWord = Beau Virgill

userSyncMsg_FTP_RequestDir = //home//V010//01//000011
userSyncMsg_FTP_ReturnDir = //home//V010//01//000011//RSP


相关业务规范如下(截图):

164143_5uBH_167415.jpg164157_ISz7_167415.jpg164223_lAtU_167415.jpg164236_VQ4q_167415.jpg


转载于:https://my.oschina.net/u/1172409/blog/170662

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值