Java web 自动备份数据库和log4j日志

利用监听自动备份

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>muju_pro</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Log4jInitServlet</servlet-name>
    <servlet-class>com.rfx.servlet.Log4jInitServlet</servlet-class>//日志初始化类
    <init-param>
      <param-name>log4j</param-name>
      <param-value>/WEB-INF/log4j.properties</param-value>//日志资源文件配置log4j,jar
    </init-param>
    <load-on-startup>1</load-on-startup>//设置服务器启动延时多久执行
  </servlet>
  <servlet-mapping>
    <servlet-name>Log4jInitServlet</servlet-name>
    <url-pattern>*.init</url-pattern>//设置映射
  </servlet-mapping>
  <listener>
    <listener-class>com.rfx.listener.ZiJianListener</listener-class>//配置监听
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>//配置日志,这里用的spring的jar包,
  </listener>
</web-app>

监听

package com.rfx.listener;

import java.util.Timer;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <p>自检监听</p>
 * @author Administrator
 *
 */
public class ZiJianListener implements ServletContextListener {
    private Timer timer=null;
    private final Log log = LogFactory.getLog(getClass());
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        timer =new Timer(true);
        //arg0.getServletContext().log("定时器已启动");//log4j
    //    System.out.println("定时器启动");
        log.info("定时器启动");
        //调用自检
        timer.schedule(new ZiJianTask(arg0.getServletContext()), 0,12*60*60*1000);
        //调用备份数据库
        timer.schedule(new DBBackUpTask(arg0.getServletContext()),0,24*60*60*1000);
        //arg0.getServletContext().log("已添加任务");
    }

}

备份数据库

package com.rfx.listener;

import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class DBBackUpTask  extends TimerTask{
    private ServletContext context=null;
    private final Log log = LogFactory.getLog(getClass());
    public  DBBackUpTask(ServletContext context) {
        this.context=context;
    }
     public static boolean exportDatabaseTool(String userName, String password, String SID, String savePath, String fileName) throws InterruptedException {  
            File saveFile = new File(savePath);  
            if (!saveFile.exists()) {// 如果目录不存在  
                saveFile.mkdirs();// 创建文件夹  
            }  
            try {  
                Process process = Runtime.getRuntime().exec("exp " + userName + "/" + password + "@" + SID + " file=" + savePath + "/" + fileName + ".dmp");  
                if(process.waitFor() == 0){//0 表示线程正常终止。   
                    return true;  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }
            return false;  
        }  
    @Override
    public void run() {
        Format format = new SimpleDateFormat("yyyyMMdd");
        String filePathString="MJku"+format.format(new Date());
          try {
            if (exportDatabaseTool("rfxmujuku", "rfx", "orcl", "D:/MuJuKuDBBeiFen", filePathString)) {  
                    System.out.println("数据库成功备份!!!");  
                } else {  
                    System.out.println("数据库备份失败!!!");  
                }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }  
        
    }

}

log4j资源文件

log4j.rootLogger=debug, stdout ,R 

### stdout ### 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy\-MM\-dd  HH\:mm\:ss}] %p  (%F:%L) - %m%n 
### R ### 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=D:/muju.log 
log4j.appender.R.MaxFileSize=100KB 
log4j.appender.R.MaxBackupIndex=5 

log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=[%d{yyyy\-MM\-dd  HH\:mm\:ss}] %p  %c - %m%n

日志初始化

package com.rfx.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;

/**
 * Servlet implementation class Log4jInitServlet
 */
@WebServlet("/Log4jInitServlet.init")
public class Log4jInitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final Log log = LogFactory.getLog(getClass());   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Log4jInitServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init() {
        String prefix = getServletContext().getRealPath("/");
        String file = getInitParameter("log4j");

        if (file != null) {
           //System.out.println("log4j 初始化成功");
        log.info("log4j初始化成功");
        PropertyConfigurator.configure(prefix+ file);
        } else {
            log.info("log4j初始化失败");
        //System.out.println("log4j 初始化失败");
        }

        }

}

自行导包

 

posted @ 2017-11-21 16:12  王怀霞  阅读(1455)  评论(1编辑  收藏  举报