Skip to content

Instantly share code, notes, and snippets.

@sheki
Created March 15, 2011 06:57
Show Gist options
  • Save sheki/870405 to your computer and use it in GitHub Desktop.
Save sheki/870405 to your computer and use it in GitHub Desktop.
A servlet which loads on Startup of a tomcat and initializes a thrift server.
package xyz.ping.server.impl;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServlet;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.server.TThreadPoolServer.Args;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportFactory;
public class InitServlet extends HttpServlet
{
public static void main(String[] args) throws Exception
{
//Scaffolding code for testing.
InitServlet s = new InitServlet();
s.init();
}
@Override
public void init()
{
try
{
System.out.println("Starting thrift service");
ThriftServer.start();
}
catch (Exception e)
{
throw new RuntimeException();
}
}
public static class ThriftServer
{
private static logger = XYZ.getLogger(ThriftServer.class);
private static TThreadPoolServer server;
public static void start() throws Exception
{
int portNo = 7911;
TServerSocket serverTransport = new TServerSocket(7911, 2000);
Processor processor = new Processor(new PingImpl());
logger.debug("Starting thrift server ");
Args args = new Args(serverTransport);
args.maxWorkerThreads = 50;
args.minWorkerThreads = 20;
args.stopTimeoutUnit = TimeUnit.SECONDS;
args.stopTimeoutVal = 10;
args.inputProtocolFactory(new TBinaryProtocol.Factory(true, true));
args.outputProtocolFactory(new TBinaryProtocol.Factory(true, true));
args.outputTransportFactory(new TTransportFactory());
args.inputTransportFactory(new TTransportFactory());
args.processor(processor);
System.out.println("thrift service, created all args");
server = new TThreadPoolServer(args);
System.out.println("thrift service, created TThreadPoolServer");
logger.debug("In Server, TThreadPool created");
new Thread()
{
@Override
public void run()
{
System.out.println("In server");
logger.debug("In Server Thread");
server.serve();
}
}.start();
System.out.println("Server started");
logger.debug("Thrift Server Started");
}
public static void stop()
{
server.stop();
}
}
}
public class PingImpl implements Iface
{
@Override
public String ping(String message) throws TException
{
return "hello " + message;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment