利用Wrapper把Java应用封装成NT Service

来源:互联网 发布:au录音软件安装 编辑:程序博客网 时间:2024/06/05 10:57

在windows环境下,有些时候,我们需要让java程序以service的形式来运行,省去那个黑窗口,在或是当java程序关闭时要去做一点事情,这种场景下这个功能就显得非常的实用了。


如果是在unix环境下,选择的就多一些,比如自己编写一段shell ,或是利用apache daemon,在或是利用wrapper for unix版,都是非常的便利。

apache daemon可以参考:使用apache daemon让java程序在unix系统上以服务方式运行 


下面我写个demo来看一下wrapper如何把java以NT Service的方式运行。

首先我们到:http://wrapper.tanukisoftware.com/doc/english/download.jsp 下载对应的 wrapper for windown版本到本地。

解压后会得到如下几个文件:

wrapper.conf

wrapper.jar

wrapper.exe

wrapper.dll


我当前的目录结构是:

c:/win32/

           |

           — wrapper.conf

           — wrapper.exe

           — wrapper.dll

           — lib

                  |

                   — wrapper.jar

                   — hook .jar

                   — other.jar

           — log


好,我们根据这个目录结构来编辑wrapper.conf,内容如下:

#********************************************************************# Wrapper Properties#********************************************************************set.default.HOOK_TEST_HOME=.set.default.HOOK_TEST_BASE=.set.default.HOOK_TEST_CONF=%HOOK_TEST_HOME%set.default.HOOK_TEST_DATA=%HOOK_TEST_HOME%/logwrapper.working.dir=.# Java Applicationwrapper.java.command=java# Java Main class.  This class must implement the WrapperListener interface#  or guarantee that the WrapperManager class is initialized.  Helper#  classes are provided to do this for you.  See the Integration section#  of the documentation for details.wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperStartStopApp# Java Classpath (include wrapper.jar)  Add class path elements as#  needed starting from 1wrapper.java.classpath.1=%HOOK_TEST_HOME%/lib/*.jarwrapper.ping.timeout=0# Java Library Path (location of Wrapper.DLL or libwrapper.so)wrapper.java.library.path.1=%HOOK_TEST_HOME%# Java Additional Parameters#wrapper.java.additional.1=# Initial Java Heap Size (in MB)wrapper.java.initmemory=3# Maximum Java Heap Size (in MB)wrapper.java.maxmemory=64# Application parameters.  Add parameters as needed starting from 1# parameter.5 is  a flag which controls whether or not the Wrapper should# wait for all non daemon threads to complete before exiting the JVMwrapper.app.parameter.1=com.jason.hook.HookTestwrapper.app.parameter.2=1wrapper.app.parameter.3=startwrapper.app.parameter.4=com.jason.hook.HookTestwrapper.app.parameter.5=TRUEwrapper.app.parameter.6=1wrapper.app.parameter.7=stop#********************************************************************# Wrapper Logging Properties#********************************************************************# Format of output for the console.  (See docs for formats)wrapper.console.format=PM# Log Level for console output.  (See docs for log levels)wrapper.console.loglevel=INFO# Log file to use for wrapper output logging.wrapper.logfile=%HOOK_TEST_DATA%/wrapper.log# Format of output for the log file.  (See docs for formats)wrapper.logfile.format=LPTM# Log Level for log file output.  (See docs for log levels)wrapper.logfile.loglevel=INFO# Maximum size that the log file will be allowed to grow to before#  the log is rolled. Size is specified in bytes.  The default value#  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or#  'm' (mb) suffix.  For example: 10m = 10 megabytes.wrapper.logfile.maxsize=0# Maximum number of rolled log files which will be allowed before old#  files are deleted.  The default value of 0 implies no limit.wrapper.logfile.maxfiles=0# Log Level for sys/event log output.  (See docs for log levels)wrapper.syslog.loglevel=NONE#********************************************************************# Wrapper NT Service Properties#********************************************************************# WARNING - Do not modify any of these properties when an application#  using this configuration file has been installed as a service.#  Please uninstall the service before modifying this section.  The#  service can then be reinstalled.# Name of the servicewrapper.ntservice.name=HookTest# Display name of the servicewrapper.ntservice.displayname=HookTest# Description of the servicewrapper.ntservice.description=Hook Test# Service dependencies.  Add dependencies as needed starting from 1wrapper.ntservice.dependency.1=# Mode in which the service is installed.  AUTO_START or DEMAND_STARTwrapper.ntservice.starttype=AUTO_START# Allow the service to interact with the desktop.wrapper.ntservice.interactive=false

编辑InstallService.bat脚本安装NT Service,内容如下:

@echo offREM ------------------------------------------------------------------------REM Licensed to the Apache Software Foundation (ASF) under one or moreREM contributor license agreements.  See the NOTICE file distributed withREM this work for additional information regarding copyright ownership.REM The ASF licenses this file to You under the Apache License, Version 2.0REM (the "License"); you may not use this file except in compliance withREM the License.  You may obtain a copy of the License atREMREM http://www.apache.org/licenses/LICENSE-2.0REMREM Unless required by applicable law or agreed to in writing, softwareREM distributed under the License is distributed on an "AS IS" BASIS,REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.REM See the License for the specific language governing permissions andREM limitations under the License.REM ------------------------------------------------------------------------setlocalrem Java Service Wrapper general NT service install scriptif "%OS%"=="Windows_NT" goto ntecho This script only works with NT-based versions of Windows.goto :eof:ntremrem Find the application home.remrem %~dp0 is location of current script under NTset _REALPATH=%~dp0set HOOK_TEST_HOME=%~dp0../win32set HOOK_TEST_BASE=%~dp0../win32:confset _WRAPPER_CONF="%HOOK_TEST_HOME%\wrapper.conf"set _HOOK_TEST_HOME="set.HOOK_TEST_HOME=%HOOK_TEST_HOME%"set _HOOK_TEST_BASE="set.HOOK_TEST_BASE=%HOOK_TEST_BASE%"remrem Install the Wrapper as an NT service.rem:startup"wrapper.exe" -i %_WRAPPER_CONF% %_HOOK_TEST_HOME% %_HOOK_TEST_BASE%if not errorlevel 1 goto :eofpause

编辑UninstallService.bat脚本用于卸载NT Service,脚本如下:

@echo offREM ------------------------------------------------------------------------REM Licensed to the Apache Software Foundation (ASF) under one or moreREM contributor license agreements.  See the NOTICE file distributed withREM this work for additional information regarding copyright ownership.REM The ASF licenses this file to You under the Apache License, Version 2.0REM (the "License"); you may not use this file except in compliance withREM the License.  You may obtain a copy of the License atREMREM http://www.apache.org/licenses/LICENSE-2.0REMREM Unless required by applicable law or agreed to in writing, softwareREM distributed under the License is distributed on an "AS IS" BASIS,REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.REM See the License for the specific language governing permissions andREM limitations under the License.REM ------------------------------------------------------------------------setlocalrem Java Service Wrapper general NT service uninstall scriptif "%OS%"=="Windows_NT" goto ntecho This script only works with NT-based versions of Windows.goto :eof:ntremrem Find the application home.remrem %~dp0 is location of current script under NTset _REALPATH=%~dp0set HOOK_TEST_HOME=%~dp0:confset _WRAPPER_CONF="%HOOK_TEST_HOME%\wrapper.conf"remrem Uninstall the Wrapper as an NT service.rem:startup"%_APP_HOME%wrapper.exe" -r %_WRAPPER_CONF%if not errorlevel 1 goto :eofpause


Hook.jar的内容很少,就一个类,内容如下:

package com.jason.hook;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;/** * @date 2013-7-2 * @author Jason */public class HookTest {static ServerSocket server = null;volatile static boolean isRun = false; /** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubif (args[0].equalsIgnoreCase("start")) {start();}else{stop();}}public static void stop(){isRun = false;System.out.println("Hook...");if (server != null) {try {System.out.println("Server.Hook.Close...");FileOutputStream out = new FileOutputStream(new File("c:\\Hook.txt"));out.write("Server.Hook.Close...".getBytes());out.flush();out.close();server.close();System.exit(0);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();System.exit(0);}}else{System.out.println("Server.Hook...server is null");System.exit(0);}}public static void start(){try {server = new ServerSocket(8000);isRun = true;System.out.println("Listener port 8000");while(isRun){try {if (server == null || server.isClosed()) {break;}Socket client = server.accept();System.out.println("有新的连接..."+client.toString());InputStream inputStream = client.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));String s = null;while((s = reader.readLine()) != null){if (s.trim().equalsIgnoreCase("exit")) {isRun = false;System.out.println("Server.exit...");if (server != null) {server.close();}if (reader != null) {reader.close();}break;}else{System.out.println("Server:"+s);}}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}System.out.println("start method: exit app");System.exit(0);} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}finally{if (server != null) {try {server.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}


接下来,我们就可以运行InstallService.bat来安装NT Service,运行UninstallService.bat来卸载这个服务。

感兴趣的可以试试,很好用!




原创粉丝点击