public class ThriftTestImpl implements ComputeServer.Iface {
private static final Logger logger = LogManager.getLogger(ThriftTestImpl.class);
public ComputeResponse getComputeResult(ComputeRequest request) {
ComputeType computeType = request.getComputeType();
long x = request.getX();
long y = request.getY();
logger.info("get compute result begin. [x:{}] [y:{}] [type:{}]", x, y, computeType.toString());
long begin = System.currentTimeMillis();
ComputeResponse response = new ComputeResponse();
response.setErrorNo(0);
try {
long ret;
if (computeType == ComputeType.ADD) {
ret = add(x, y);
response.setComputeRet(ret);
} else if (computeType == ComputeType.SUB) {
ret = sub(x, y);
response.setComputeRet(ret);
} else if (computeType == ComputeType.MUL) {
ret = mul(x, y);
response.setComputeRet(ret);
} else {
ret = div(x, y);
response.setComputeRet(ret);
}
} catch (Exception e) {
response.setErrorNo(1001);
response.setErrorMsg(e.getMessage());
logger.error("exception:", e);
}
long end = System.currentTimeMillis();
logger.info("get compute result end. [errno:{}] cost:[{}ms]", response.getErrorNo(), (end - begin));
return response;
}
private long add(long x, long y) {
return x + y;
}
private long sub(long x, long y) {
return x - y;
}
private long mul(long x, long y) {
return x * y;
}
private long div(long x, long y) {
return x / y;
}
}
public class ServerMain {
private static final Logger logger = LogManager.getLogger(ServerMain.class);
public static void main(String[] args) {
try {
//实现服务处理接口impl
ThriftTestImpl workImpl = new ThriftTestImpl();
//创建TProcessor
TProcessor tProcessor = new ComputeServer.Processor<ComputeServer.Iface>(workImpl);
//创建TServerTransport,非阻塞式 I/O,服务端和客户端需要指定 TFramedTransport 数据传输的方式
final TNonblockingServerTransport transport = new TNonblockingServerSocket(9999);
//创建TProtocol
TThreadedSelectorServer.Args ttpsArgs = new TThreadedSelectorServer.Args(transport);
ttpsArgs.transportFactory(new TFramedTransport.Factory());
//二进制格式反序列化
ttpsArgs.protocolFactory(new TBinaryProtocol.Factory());
ttpsArgs.processor(tProcessor);
ttpsArgs.selectorThreads(16);
ttpsArgs.workerThreads(32);
logger.info("compute service server on port :" + 9999);
//创建TServer
TServer server = new TThreadedSelectorServer(ttpsArgs);
//启动Server
server.serve();
} catch (Exception e) {
logger.error(e);
}
}
}
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) | Powered by Discuz! X3.2 |