java编写service详细笔记 - centos7.2实战笔记(windows类似就不在重复了)
目标效果(命令行启动服务):
service xxxxd start #启动服务
service xxxxd stop #停止服务
详细步骤
一、编译并安装jsvc
官网 https://commons.apache.org/daemon/
1)建立目录
cd /
mkdir jsvc
2)下载jsvc源码
wget https://mirrors.tuna.tsinghua.edu.cn/apache//commons/daemon/source/commons-daemon-1.0.15-src.tar.gz
3)解压源码
tar zxvf commons-daemon-1.0.15-src.tar.gz
4)编译源码
编译器为了省事,先给目录下所有文件设置可执行权限
chmod -R 777 *
cd /jsvc/commons-daemon-1.0.15-src/src/native/unix
./support/buildconf.sh
./configure --with-java=/opt/jdk #注 /opt/jdk 是我的java安装目录
make #编译
5)编译后
会在 /jsvc/commons-daemon-1.0.15-src/src/native/unix 生成 可执行文件jsvc
设置一下执行权限
chmod 777 /jsvc/commons-daemon-1.0.15-src/src/native/unix/jsvc
二、实战编写一个小小的javasocket服务,代码如下:
1)test_service.java
========================================================================
package com.xiaobaijiuxing.jsvc;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
/**
* @date 2017-5-2
* @author 小白救星
*/
public class test_service implements Daemon {
public static boolean isstop = false;
public static void main(String args[]) {
System.out.println("Hello World2!");
}
/* (non-Javadoc)
* @see org.apache.commons.daemon.Daemon#destroy()
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("JsvcTest destory method...");
}
/* (non-Javadoc)
* @see org.apache.commons.daemon.Daemon#init(org.apache.commons.daemon.DaemonContext)
*/
@Override
public void init(DaemonContext ctx) throws DaemonInitException, Exception {
// TODO Auto-generated method stub
System.out.println("JsvcTest init method..." + ctx.toString());
}
/* (non-Javadoc)
* @see org.apache.commons.daemon.Daemon#start()
*/
@Override
public void start() throws Exception {
// TODO Auto-generated method stub
int i =0;
//while (!isstop)
//{
Server server = new Server();
server.init();
System.out.println("JsvcTest start method..." + i);
i = i +1;
//}
}
/* (non-Javadoc)
* @see org.apache.commons.daemon.Daemon#stop()
*/
@Override
public void stop() throws Exception {
// TODO Auto-generated method stub
isstop = true;
System.out.println("JsvcTest stop method...");
}
}
========================================================================
2)Server.java
========================================================================
package com.xiaobaijiuxing.jsvc;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static final int PORT = 12345;//监听的端口号
//public static void main(String[] args) {
// System.out.println("服务器启动...\n");
// Server server = new Server();
// server.init();
//}
public void init() {
System.out.println("服务器启动...\n");
try {
ServerSocket serverSocket = new ServerSocket(PORT);
//while (true) {
// 一旦有堵塞, 则表示服务器与客户端获得了连接
Socket client = serverSocket.accept();
// 处理这次连接
new HandlerThread(client);
//}
} catch (Exception e) {
System.out.println("服务器异常: " + e.getMessage());
}
}
private class HandlerThread implements Runnable {
private Socket socket;
public HandlerThread(Socket client) {
socket = client;
new Thread(this).start();
}
public void run() {
try {
// 读取客户端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
String clientInputStr = input.readUTF();//这里要注意和客户端输出流的写方法对应,否则会抛 EOFException
// 处理客户端数据
System.out.println("客户端发过来的内容:" + clientInputStr);
// 向客户端回复信息
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
System.out.print("请输入:\t");
// 发送键盘输入的一行
String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
out.writeUTF(s);
out.close();
input.close();
} catch (Exception e) {
System.out.println("服务器 run 异常: " + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
socket = null;
System.out.println("服务端 finally 异常:" + e.getMessage());
}
}
}
}
}
}
========================================================================
三、将我们的java代码打包到test_service.jar
我采用ant打包,因为我感觉ant最简单,写代码只要用好了EditPlus+ant就可以,不需要其它开发工具
1)ant编译配置文件build.xml
========================================================================
<?xml version="1.0" encoding="UTF-8" ?>
<project name="test_service" default="run" basedir=".">
<property name="src" value="src"/>
<property name="dest" value="classes"/>
<property name="doc.dir" value="doc"/>
<property name="test_services_jar" value="test_service.jar"/>
<property name="main.class" value="com.xiaobaijiuxing.jsvc.test_service"/>
<path id="lib_classpath">
<fileset dir="lib/">
<include name="*.jar"/>
</fileset>
</path>
<target name="init">
<mkdir dir="${dest}"/>
</target>
<target name="compile" depends="init">
<javac encoding="utf-8" srcdir="${src}" destdir="${dest}" includeantruntime="on">
<classpath refid="lib_classpath"/>
</javac>
</target>
<target name="build" depends="compile">
<jar encoding="utf-8" jarfile="${test_services_jar}" basedir="${dest}">
<manifest>
<!--<attribute name="Main-Class" value="${main.class}"/>-->
<attribute name="Class-Path" value="lib/commons-daemon-1.0.15.jar"/>
</manifest>
</jar>
</target>
<target name="run" depends="clean,build">
</target>
<target name="clean">
<delete dir="${dest}" />
<delete file="test_services_jar" />
</target>
<target name="rerun" depends="clean,run">
<ant target="clean" />
<ant target="run" />
</target>
<target name="createdoc">
<delete dir="${doc.dir}" />
<mkdir dir="${doc.dir}"/>
<javadoc destdir="${doc.dir}" encoding="UTF-8" docencoding="UTF-8">
<packageset dir="${src}">
<include name="**"/>
</packageset>
</javadoc>
</target>
</project>
========================================================================
2)编译生成test_service.jar包
命令行运行 ant回车即可
3)建立目录
mkdir /jsvc/commons-daemon-1.0.15-src/app
mkdir /jsvc/commons-daemon-1.0.15-src/log
mkdir /jsvc/commons-daemon-1.0.15-src/tmp
chmod -R 777 *
4)将编译出来的jar包及要用到的lib目录拷贝到 /jsvc/commons-daemon-1.0.15-src/app 目录下
app目录下是 test_service.jar
app/lib目录下是 commons-daemon-1.0.15.jar
四、编写linux centos7.2 service 脚本并运行
1)cd /etc/init.d/
2)vi testserviced #内容如下
========================================================================
#!/bin/sh
RETVAL=0
prog="jsvc"
JAVA_HOME=/opt/jdk
APP_HOME=/jsvc/commons-daemon-1.0.15-src/app
#jsvc所在的目录
DAEMON_HOME=/jsvc/commons-daemon-1.0.15-src/src/native/unix
APP_USER=root
TMP_DIR=/jsvc/commons-daemon-1.0.15-src/app/tmp
PID=/jsvc/commons-daemon-1.0.15-src/app/testserviced.pid
CLASSPATH=/jsvc/commons-daemon-1.0.15-src/app/test_service.jar:/jsvc/commons-daemon-1.0.15-src/app/lib/commons-daemon-1.0.15.jar
case "$1" in
start)
#echo $DAEMON_HOME
# Start Serivce
$DAEMON_HOME/jsvc -user $APP_USER -home $JAVA_HOME -Djava.io.tmpdir=$TMP_DIR -wait 5000 -pidfile $PID -outfile $APP_HOME/log/jsvc.out -errfile '&1' -cp $CLASSPATH com.jason.jsvc.test_service &
# To get a verbose JVM
#-verbose \
# To get a debug of jsvc.
#-debug \
exit $?
;;
stop)
#
# Stop Serivce
#
#$DAEMON_HOME/jsvc -stop -pidfile $PID com.jason.jsvc.test_service
exit $?
;;
*)
echo "Usage service testserviced start/stop"
exit 1;;
esac
:wq #保存
========================================================================
3)添加centos系统服务
chmod 777 /etc/init.d/testserviced
chkconfig --add testserviced
4)启动和关闭服务
service testserviced start
查看我们服务启动后的socket服务端口是否启动了监听
lsof -i:12345
返回结果:
[root@xiaobaijiuxing ~]# lsof -i:12345
[root@xiaobaijiuxing ~]# service testserviced start
[root@xiaobaijiuxing ~]# lsof -i:12345
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
jsvc 171926 root 9u IPv6 5672748 0t0 TCP *:italk (LISTEN)
service testserviced stop
五、大功告成
作者:小白救星 原创,未经许可可以随意转发