How to load and execute Thread class when spring configuration loaded (如何在读取spring配置时自启动线程类)

来源:互联网 发布:淘宝卖的白酒是假酒吗 编辑:程序博客网 时间:2024/05/18 01:31

场景:需求要求当应用启动的时候进行系统一些统计工作。

解决方案:在不改变原有启动类的条件下,添加配置影响范围比较小,以线程的方式实时记录系统运行状况。

实例:系统统计类:SystemUsageThread.java

在spring配置文件加如下代码:

<beans>
     <bean id="SystemUsageGatheringDataService" 
        class="com.cpcus.jaru.biz.impl.SystemUsageGatheringDataService"
          lazy-init="false" scope="singleton">
     </bean>
</beans>

推荐创建该类的ctx配置文件,这样的好处是做junit测试的时候如果用到了spring的配置就可以避免每次都会启动线程,造成junit测试的干扰。

创建文件名:SystemUsageGatheringDataService.ctx.xml 。代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
     <bean id="SystemUsageGatheringDataService" 
        class="com.cpcus.jaru.biz.impl.SystemUsageGatheringDataService"
          lazy-init="false" scope="singleton">
     </bean>
</beans>


Note:lazy-init最好显示的说明是false或者true,避免默认值是true导致实例不能被创建。如果只需要一个实例,最好声明scope="singleton"。


线程类的部分代码贴出,主要是一部分逻辑功能的展示。

/**
 * The class for record system usage statistic and initialed when
 * spring configuration is loaded.
 * @author Angel.Fu
 *
 */
public class SystemUsageGatheringDataService implements Runnable,
IBusinessLayerInterface, ISystemLifecycle
{
  private static final Logger log = LoggerFactory.getLogger(SystemUsageGatheringDataService.class);

  private final int ONE_MINUTE_MILLINSECONDS = 60 * 1000;
  private final int ONE_HOUR_MILLINSECONDS = 60 * ONE_MINUTE_MILLINSECONDS;
  private IJaruStats stats = null;
  private SystemUsageSummaryBean latestSystemUsage = null;
  private Long machineId = null;
  private Thread gatheringSystemUsage = null;
  private boolean isShutDown = false;
  /**
   * The default constructor for run the thread of system
   * resource usage log record.
   */
  public SystemUsageGatheringDataService()
  {
    this.gatheringSystemUsage = new Thread(this, "SystemUsageGatheringDataService");
    this.gatheringSystemUsage.start();
  }
  
  /**
   * check the missed Log record and save the missed record.
   */
  private void checkAndUpdateMissedLogRecord()
  {
    
  }
  
  /**
   * Update the old display log and generate the latest display log.
   * @param displayLog the display log for update.
   */
  private void makeValidSystemUsageSummaryLog(SystemUsageSummaryBean displayLog)
  {
 
  }
  
 
  /**
   * Initial some parameters before execute thread.
   */
  private void initialConfiguration()
  {
    log.debug("Initial the configured data before record system usage.");
    IBusinessServices bizServices = BusinessServicesImpl.getInstance();
    stats = (IJaruStats) bizServices.getInterface(IJaruStats.class);
    RemoteInterfaceMarshaller remoteInterfaceMarshaller =
      RemoteInterfaceMarshaller.getInstance();
    machineId = remoteInterfaceMarshaller.getLocalMachineContext().getId();
  }


  
  /**
   * {@inheritDoc}
   * @see Runnable#run();
   */
  public void run()
  {
    initialConfiguration();
    checkAndUpdateMissedLogRecord();
    while (!isShutDown)
    {
      try
      {
        recordSystemUsageLog();
        Thread.sleep(ONE_MINUTE_MILLINSECONDS);
      } 
      catch (InterruptedException e)
      {
        log.error("System usage thread interrupted ...", e);
      }
      catch (Exception e)
      {
        log.error("The unknown runtime exception throwed: " + e.getMessage(), e);
      }
    }
  }
  
  /**
   * Record the system usage log by interval.
   */
  private void recordSystemUsageLog()
  {
    
  }


  /**
   * Save the per hour system usage data.
   * 
   * @param tempLog the temporary of display log for update.
   */
  private void updateSystemUsageSummaryLog(SystemUsageSummaryBean tempLog)
  {

  }
    
  /**
   * Save the temporary display log of system usage for per hour.
   * @param recordDate the date of log record.
   */
  private void saveTempPerHourSystemUsageLog(Date recordDate)
  {
  } 
  
  /**
   * Is the specified system usage summary bean invalid?
   * 
   * @param summaryLog System usage summary bean.
   * @return true when the system usage summary bean is created only without any
   *         real value, this can happen when no detail log records exist for
   *         the summary bean.
   */
  private boolean isInvalidSummaryLog(SystemUsageSummaryBean summaryLog)
  {
   
  }
  
  /**
   * {@inheritDoc}
   * @see ISystemLifecycle#init();
   */
  public void init()
  {
  }
  
  /**
   * {@inheritDoc}
   * @see ISystemLifecycle#destroy();
   */
  public void destroy()
  {
    this.isShutDown = true;
    this.gatheringSystemUsage.interrupt();
  }

}


实际显示效果图。



0 0
原创粉丝点击