Java用JavaService实现Windows系统服务

来源:互联网 发布:mac os x 升级 编辑:程序博客网 时间:2024/06/05 02:20

 Java项目中需要用到系统启动后就自动执行某功能的需求,自然而然想到的是Windows服务(NT服务),虽然C或者C++也能实现它,但是这里用到了开源的JavaService来实现,其项目地址为:http://javaservice.objectweb.org,可以在上面下载JavaService.exe,也可以在CSDN下载:http://download.csdn.NET/detail/sky1718/9487085

        下面开始实现NT服务。这里需要用到两个类,一个是控制NT服务启动和停止的类,另外一个是实现NT服务的线程类。如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class TestService {  
  2.     private static Thread thread = null;  
  3.     private static Service service = null;  
  4.       
  5.     public static void stopService(String[] args){  
  6.         service.setServiceStatu(false);  
  7.     }  
  8.       
  9.     public static void startService(String[] args){  
  10.         service = new Service();  
  11.         thread = new Thread(service);  
  12.         try{  
  13.             // 将服务线程设定为用户线程  
  14.             thread.setDaemon(false);  
  15.             if(!thread.isDaemon()){  
  16.                 System.out.println("[" + new Date() + "]成功设定为用户线程!");  
  17.             }  
  18.             thread.start();  
  19.         }catch(SecurityException e){  
  20.             e.printStackTrace();  
  21.         }catch(Exception e){  
  22.             e.printStackTrace();  
  23.         }  
  24.     }  
  25.       
  26.     public static void main(String [] args){  
  27.         startService(args);  
  28.     }  
  29. }  
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class Service implements Runnable {  
  2.   
  3.     private boolean serviceStatu = true;  
  4.       
  5.     public synchronized void setServiceStatu(boolean serviceStatu){  
  6.         this.serviceStatu = serviceStatu;  
  7.     }  
  8.       
  9.     private synchronized boolean getServiceStatu(){  
  10.         return serviceStatu;  
  11.     }  
  12.       
  13.     @Override  
  14.     public void run() {  
  15.         try {  
  16.             while(getServiceStatu()){  
  17.                 System.out.println("[" + new Date() + "]服务运行中...");  
  18.             }  
  19.         }catch (Exception e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.   
  23.     }  
  24. }  

        这里有两个问题需要注意:

        1.方法StartService和StopService都拥有参数,在安装NT服务的时候,我们可以指定启动或停止服务的参数。

        2.在启动线程之前,我们必须将线程设定为用户线程,因为如果线程是一个后台线程,则当主程序结束后JVM会自动退出,后台线程也就终止执行,而如果主程序结束时还有用户线程在运行则JVM不会自动退出,而是要等到用户线程结束后才退出,所以要保证你的服务正常运行,这个需要特别注意。

        我们可以写一个main方法测试下服务是否可以正常运行。这里的setServiceStatu和getServiceStatu两个方法是用于设定线程是正在否运行的状态,setServiceStatu需要在类外被调用并通过设定不同的参数来通知线程是否继续执行,由于会有不同的线程对线程运行状态进行设定和读取,所以这里的方法被设定为同步方法。

        服务编写完成后,下面就可以用JavaService部署运行编译好的程序了,必要时还可以将程序打包成jar文件。

        将JavaService.exe置于编译之后的服务程序所在的目录中,或者将JavaService.exe所在目录添加到环境变量PATH中。

        JavaService提供了8个参数可供选择,这里使用-install参数安装NT服务时还需要提供与服务相关的其它一些参数,其命令格式如下:
JavaService -install service_name jvm_library [jvm_options]
        -start start_class [-method start_method] [-params (start_parameters)]
        [-stop start_class [-method stop_method] [-params (stop_parameters)]]
        [-out out_log_file] [-err err_log_file]
        [-current current_dir]
        [-path extra_path]
        [-depends other_service]
        [-auto | -manual]
        [-shutdown seconds]
        [-user user_name -password password]
        [-append | -overwrite]
        [-startup seconds]
        [-description service_desc]


        相关参数的作用说明如下:

service_name: The name of the service.
 jvm_library:   The location of the JVM DLL used to run the service.
 jvm_option:   An option to use when starting the JVM, such as:"-Djava.class.path=c:/classes" or "-Xmx128m".
 start_class:   The class to load when starting the service.
 start_method: The method to call in the start_class. default: main
 start_parameters: Parameter(s) to pass in to the start_method.
 stop_class:   The class to load when stopping the service.
 stop_method:   The method to call in the stop_class. default: main
 stop_parameters:      Parameter(s) to pass in to the stop_method.
 out_log_file: A file to redirect System.out into. (gets overwritten)
 err_log_file: A file to redirect System.err into. (gets overwritten)
 current_dir:   The current working directory for the service.Relative paths will be relative to this directory.
 extra_path:   Path additions, for native DLLs etc. (no spaces)
 other_service: Single service name dependency, must start first.
 auto / manual: Startup automatic (default) or manual mode.
 seconds:       Java method processing time (startup:sleep, shutdown:timeout).
 user_name:    User specified to execute the service (user@domain).
 password:     Password applicable if user specified to run the service.
 append / overwrite:   Log file output mode, append (default) or overwrite.
 service_desc:   Text describing installed service (quoted string, max 1024).


        下面的命令是我自己项目中安装NT服务:

JavaService.exe  -install  TestService   "%JAVA_HOME%"/jre/bin/server/jvm.dll    -Xmx128m   -Djava.class.path="%JAVA_HOME%"/lib/tools.jar;"%CD%"/lib/jtds-1.2.5.jar;"%CD%" -start com.azure.TestService  -method  startService  -stop  com.azure.TestService  -method stopService -out "%CD%"/log/log.log -err "%CD%"/log/error.log  -current  "%CD%"  -auto


        成功安装服务后就可以用以下命令对其进行卸载,启动和停止操作了。

        JavaService.exe -uninstall TestService

        net start TestService

        net stop TestService

0 0