JAVA 实现自动监听并更新配置文件内容

自动监听器 PropertiesListener

package  org.stephencat.listener;

import  javax.servlet. * ;

/**
 * 自动监听器
 * 
@author  stephen
 *
 
*/
public   class  PropertiesListener  implements  ServletContextListener  {
    
    
/**
     * 自动监听时钟
     
*/
    
private  PropertiesTimer rt  =   null ;
    
    
public   void  contextInitialized(ServletContextEvent event) {
        String status 
=   " Properties listener start . " ;
        event.getServletContext().log(status);
        System.out.println(status);
        
        
//  激活自动监听时钟
        rt  =   new  PropertiesTimer( 15 , event.getServletContext());
        rt.start();
    }
    
    
public   void  contextDestroyed(ServletContextEvent event) {
        String status 
=   " Properties listener stop . " ;
        event.getServletContext().log(status);
        System.out.println(status);
        
        
//  停止自动监听时钟
         if  (rt  !=   null ) {
            rt.stop();
        }
    }
}

自动监听时钟 PropertiesTimer

package  org.stephencat.listener;
import  java.util. * ;
import  javax.servlet. * ;


/**
 * 自动监听时钟
 * 
@author  stephen
 *
 
*/
public   class  PropertiesTimer {
    
    
private   final  Timer timer  =   new  Timer();
    
private   final   int  sec;
    
private  ServletContext context  =   null ;
    
    
public  PropertiesTimer( int  seconds, ServletContext context) {
        sec 
=  seconds;
        
this .context  =  context;
    }
    
    
/**
     * 启动自动监听任务
     
*/
    
public   void  start() {
        
        
//  取得当前日期时间
        Date date  =   new  Date();
        
        
//  执行自动监听计划
        timer.schedule( new  PropertiesTask( this .context), date, sec  *   1000 );
    }
    
    
/**
     * 停止自动监听任务
     
*/
    
public   void  stop() {
        timer.cancel();

    }

}

自动监听任务 PropertiesTask

package  org.stephencat.listener;
import  java.io.IOException;
import  java.io. * ;
import  java.util. * ;

import  javax.servlet. * ;
/**
 * 自动监听任务
 * 
@author  stephen
 *
 
*/
public   class  PropertiesTask  extends  TimerTask {
    
    
private  ServletContext context  =   null ;
    
/**
     * 配置文件的最后更新时间
     
*/
    
private   long  lastModified  =   0 ;
    
    
/**
     * 构造一个自动更新任务
     * 
@param  context
     
*/
    
public  PropertiesTask(ServletContext context){
        
this .context  =  context;
        System.out.println(
" A task instance is created now. " );  //  任务在整个 application 周期内只创建一次。
    }
    
    
/**
     * 每次执行任务时显示一个随机数。
     
*/
    
public   void  todoTestRandom(){
        System.out.println(
" Task running " );
        context.setAttribute(
" random " , String.valueOf(Math.random()));
        System.out.println((String)context.getAttribute(
" random " ));
    }
    
    
/**
     * 监听配置文件是否被更新。
     
*/
    
public   void  todoTestFileStatus(){
        System.out.println(
" Getting file status " );
        System.out.println(
this .isFileUpdated( " WEB-INF/platforms/test.properties " ));
    }
    
    
/**
     * 监听配置文件是否被更新,自动更新文件中的配置项存储到 application 变量中。
     
*/
    
public   void  todo(){
        String filename 
=   " WEB-INF/platforms/test.properties " ;
        
if ( this .isFileUpdated(filename)){
            
            System.out.println(
" Getting properties " );
            
try {
                
this .loadProperties( " test " , filename);
            }
catch (IOException ioe){
                System.err.println(ioe.getMessage());
            }
        }
        System.out.println(
" Test value is:  "   +   this .getTestProperty( " name " ));
    }
    
    
public   void  run() {
        todoTestRandom();
        todo();
        
// todo();
    }
    
    
/**
     * 判断物理文件是否已被更新
     * 
@param  filename 物理文件名
     * 
@return  是 true 否 false
     
*/
    
private   boolean  isFileUpdated(String filename){
        File file 
=   new  File(context.getRealPath(filename));
        
if (file.isFile()){
            
long  lastUpdateTime  =  file.lastModified();
            
if (lastUpdateTime  >   this .lastModified){
                System.out.println(
" The properties file was modified. " );
                
this .lastModified  =  lastUpdateTime;
                
return   true ;
            }
else {
                System.out.println(
" The properties file was not modified. " );
                
return   false ;
            }
        }
else {
            System.out.println(
" The path does not point to a file. " );
            
return   false ;
        }
    }
    
    
/**
     * 获取配置文件
     * 
@param  key
     * 
@param  filename
     * 
@return
     
*/
    
public   void  loadProperties(String key, String filename)  throws  IOException{
        Properties prop 
=   new  Properties();
        InputStream stream 
=  context.getResourceAsStream(filename);
        prop.load(stream);
        
if (stream != null ){
            stream.close();
        }
        context.setAttribute(key, prop);
    }
    
    
/**
     * 从 application 取配置项的值
     * 
@param  key 配置项的键名
     * 
@return  配置项的值
     
*/
    
public  String getTestProperty(String key){
        Properties prop 
=  (Properties)context.getAttribute( " test " );
        
if (prop == null ){
            
return   null ;
        }
else {
            
return  (String)prop.get(key);
        }
    }

}

web.xml 配置

<? xml version="1.0" encoding="GB18030" ?>
< web-app  version ="2.4"  
    xmlns
="http://java.sun.com/xml/ns/j2ee"  
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>
     
< listener >
    
< listener-class > org.stephencat.listener.PropertiesListener </ listener-class >
</ listener >     
</ web-app >

在 WEB-INF 目录下增加 platforms/test.properties 文件

name = Stephen Wong

启动应用服务器,控制台输出如下:

11:30:31,000 INFO  [TomcatDeployer] undeploy, ctxPath=/ServerTest, warUrl=.../deploy/ServerTest.war/
11:30:31,000 INFO  [[/ServerTest]] Properties listener stop .
11:30:31,000 INFO  [STDOUT] Properties listener stop .
11:30:31,046 INFO  [TomcatDeployer] deploy, ctxPath=/ServerTest, warUrl=.../deploy/ServerTest.war/
11:30:31,359 INFO  [[/ServerTest]] Properties listener start .
11:30:31,359 INFO  [STDOUT] Properties listener start .
11:30:31,375 INFO  [STDOUT] A task instance is created now.
11:30:31,390 INFO  [STDOUT] Task running
11:30:31,390 INFO  [STDOUT] 0.9924364802139768
11:30:31,390 INFO  [STDOUT] The properties file was modified.
11:30:31,390 INFO  [STDOUT] Getting properties
11:30:31,390 INFO  [STDOUT] Test value is: Stephen
11:30:46,390 INFO  [STDOUT] Task running
11:30:46,390 INFO  [STDOUT] 0.24869896604923036
11:30:46,390 INFO  [STDOUT] The properties file was not modified.
11:30:46,390 INFO  [STDOUT] Test value is: Stephen
11:31:01,390 INFO  [STDOUT] Task running
11:31:01,390 INFO  [STDOUT] 0.47994173379307203
11:31:01,390 INFO  [STDOUT] The properties file was not modified.
11:31:01,390 INFO  [STDOUT] Test value is: Stephen
11:31:16,390 INFO  [STDOUT] Task running
11:31:16,390 INFO  [STDOUT] 0.6379331056768383
11:31:16,390 INFO  [STDOUT] The properties file was modified.
11:31:16,390 INFO  [STDOUT] Getting properties
11:31:16,390 INFO  [STDOUT] Test value is: Stephen Wong
11:31:31,390 INFO  [STDOUT] Task running
11:31:31,390 INFO  [STDOUT] 0.30415561271978353
11:31:31,390 INFO  [STDOUT] The properties file was not modified.
11:31:31,390 INFO  [STDOUT] Test value is: Stephen Wong
11:31:46,390 INFO  [STDOUT] Task running
11:31:46,390 INFO  [STDOUT] 0.03696303208126983
11:31:46,390 INFO  [STDOUT] The properties file was not modified.
11:31:46,390 INFO  [STDOUT] Test value is: Stephen Wong








我自己地例子

package cn.gov.luzhou.SiteServer.gate.web.filter;

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

import cn.gov.luzhou.SiteServer.gate.buiness.service.SysUserService;
import cn.gov.luzhou.SiteServer.gate.buiness.util.AppContext;

/**
 *
 * @author  向才鹏
 * @version  1.0
 * Copyright (C), 2009,www.soujava.cn所有
 * Program Name:鹏哥伟业
 * Date: Nov 5, 2010 10:41:34 AM
 */
@SuppressWarnings("unused")
public class PropertiesListener implements ServletContextListener{
 private SysUserService userSev;
 
    private PropertiesTimer rt = null;
    public void contextInitialized(ServletContextEvent event) {
        String status = "updatecenter listener start .";
        event.getServletContext().log(status);
        
        ServletContext sc = event.getServletContext();
        if(sc.getInitParameter("udpateCenterSwitch").equals("open")){
          userSev = (SysUserService) AppContext.getBean("sysUserService");
             // 激活自动监听时钟
            rt = new PropertiesTimer(15,sc,userSev);
            rt.start();
        }
    }
    
    public void contextDestroyed(ServletContextEvent event) {
        String status = "updatecenter listener stop .";
        event.getServletContext().log(status);
        System.out.println(status);
        
        // 停止自动监听时钟
        if (rt != null) {
            rt.stop();
        }
        userSev = null;
    }

    
 public SysUserService getUserSev() {
  return userSev;
 }

 public void setUserSev(SysUserService userSev) {
  this.userSev = userSev;
 }

 public PropertiesTimer getRt() {
  return rt;
 }

 public void setRt(PropertiesTimer rt) {
  this.rt = rt;
 }
}





package cn.gov.luzhou.SiteServer.gate.web.filter;

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

import javax.servlet.ServletContext;

import cn.gov.luzhou.SiteServer.gate.buiness.service.SysUserService;


/**
 *
 * @author  向才鹏
 * @version  1.0
 * Copyright (C), 2009,www.soujava.cn所有
 * Program Name:鹏哥伟业
 * Date: Nov 5, 2010 10:59:46 AM
 */
public class PropertiesTimer {
 private final Timer timer = new Timer();
    private final int sec;
    private ServletContext context = null;
    private SysUserService userSev = null;
    
    public PropertiesTimer(int seconds, ServletContext context,SysUserService userSev) {
        sec = seconds;
        this.context = context;
    }
    
    /**
     * 启动自动监听任务
     */
    public void start() {
        
        // 取得当前日期时间
        Date date = new Date();
        
        // 执行自动监听计划
        timer.schedule(new PropertiesTask(this.context,userSev), date, sec * 1000);
    }
    
    /**
     * 停止自动监听任务
     */
    public void stop() {
        timer.cancel();
        userSev = null;
    }
}





package cn.gov.luzhou.SiteServer.gate.web.filter;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.TimerTask;

import javax.servlet.ServletContext;

import cn.gov.luzhou.SiteServer.gate.buiness.service.SysUserService;
import cn.gov.luzhou.SiteServer.gate.buiness.util.AppContext;

public class PropertiesTask extends TimerTask{
 private ServletContext context = null;
 SysUserService userSev = null;
    /**
  * 构造一个自动更新任务
  * @param context
  */
    public PropertiesTask(ServletContext context,SysUserService ttt){
        this.context = context;
        if(ttt==null){
         this.userSev = (SysUserService) AppContext.getBean("sysUserService");
        }else{
         this.userSev = ttt;
        }
    }
    
    public void run() {
        todoTestRandom();
        todo();
    }
    
    /**
  * 每次执行任务时显示一个随机数。
  */
    public void todoTestRandom(){
        context.setAttribute("random", String.valueOf(Math.random()));
    }
    
    
    /**
  * 自动更新文件中的配置项存储到 application 变量中。
  */
    public void todo(){
     Timestamp st = new Timestamp(Calendar.getInstance().getTimeInMillis());
     context.log(st.toString()+"自动更新了数据");
     userSev.updateAll();
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值