Thursday, April 10, 2014

Run your jar as a server on Linux

Recently, I was experimenting with Apache Thrift. Then I decided to upload my server jar file onto RHEL server and connect to it with my client from my machine.

The set up was pretty simple. I generated jar file with NetBeans. This gave me actual jar file and a lib folder. I uploaded them to RHEL server and ran it

 java -cp AdditionThriftSample.jar com.blogspot.alkrinker.samples.thrift.server.MyServer

Saw

Starting the simple server on 9091...

and I was able to connect to it from my Thrift client.

Now... I wanted to go a step further and make my thrift server to be a service. Here is what I did:

Create the start and the stop script of your application. Make sure to chmod them so they can be executed. Put it on some directory, in our example is:
  • Start Script: /usr/local/bin/AdditionThriftSample-start.sh
  • Stop Script: /usr/local/bin/AdditionThriftSample-stop.sh
Sample of the AdditionThriftSample-start.sh content:
#!/bin/bash java -cp AdditionThriftSample.jar com.blogspot.alkrinker.samples.thrift.server.MyServer

Sample of the stop script:
#!/bin/bash
# Grabs and kill a process from the pidlist that has the word myapp
pid=`ps aux | grep AdditionThriftSample | awk '{print $2}'`
kill -9 $pid

Now make it a service! Create the following script (thriftserver) and put it on /etc/init.d.
/etc/init.d/thriftserver content:

#!/bin/bash
# thriftserver
#

case $1 in
    start)
        /bin/bash /usr/local/bin/AdditionThriftSample-start.sh
    ;;
    stop)
        /bin/bash /usr/local/bin/AdditionThriftSample-stop.sh
    ;;
    restart)
        /bin/bash /usr/local/bin/AdditionThriftSample-stop.sh
        /bin/bash /usr/local/bin/AdditionThriftSample-start.sh
    ;;
esac
exit 0

Put the script to start with the system (using SysV). Just run the following command (as root):

update-rc.d thriftserver defaults 
 
Credits:

No comments:

Post a Comment