zeromq 服务端开启了20个线程,客服端会发送6000个请求过来; 在处理1000个请求的时候,速度很快,一口气就跑完了, 在处理一千到三千的请求的时候,中间总是停一会,跑一会, 到了三千以后停的时间越来越长,到四千左右就不动了. 有时候会报"gc开销过大",调了gc之后.还是没有多大的作用, 但是呢:当我把服务端的线程只开启一个的时候,就能顺利跑完, 下面是服务端的代码
/**
* 多线程 NLP 服务器
*/
public class mtserver {
/*默认为20个NLP线程*/
static Integer WORKERNUM = 20;
private static class HeronlpWorker extends Thread {
private ZContext context;
private MyUncaughtExceptionhandler myUncaughtException;
public void setMyUncaughtException(MyUncaughtExceptionhandler myUncaughtException) {
this.myUncaughtException = myUncaughtException;
}
private HeronlpWorker(ZContext context) {
this.context = context;
}
@Override
public void run() {
Socket socket = context.createSocket(SocketType.REP);
myUncaughtException.setSkt(socket);
socket.connect("inproc://workers");
HeroNLP heroNLP = new HeroNLP();
String result = null;
String msgType = "";
while (true) {
try {
//接收命令
String command = socket.recvStr(0).trim();
System.out.println(Thread.currentThread().getName() + " Received request: [" + command + "]");
String content = null;
switch (command){
//分词
case "SEGMENT":
content = socket.recvStr(0).trim();
List<Term> terms = NLP.segment(content);
result = listToString(terms, " ");
break;
default:
while (socket.hasReceiveMore()){
socket.recvStr(0).trim();
}
result = "FAILED: 未匹配到命令!";
break;
}
} catch (Exception e) {
result = "FAILED:" + e.getMessage();
}
// 给客户端返回结果(C字符串)
System.out.println("是否有异常: " + result.contains("FAILED:"));
if(result.contains("FAILED:")){
msgType = "FAILED";
}
socket.send(msgType, 2);
socket.send(result, 0);
}
}
}
public static void main(String[] args) {
try (ZContext context = new ZContext()) {
//前端--router
Socket clients = context.createSocket(SocketType.ROUTER);
boolean bind = clients.bind("tcp://*:9002");
//后端--dealer
Socket workers = context.createSocket(SocketType.DEALER);
workers.bind("inproc://workers");
//后端启动20个服务线程
for (int thread_nbr = 0; thread_nbr < WORKERNUM; thread_nbr++) {
Thread nlpworker = new HeronlpWorker(context);
MyUncaughtExceptionhandler myUncaughtExceptionhandler = new MyUncaughtExceptionhandler();
((HeronlpWorker) nlpworker).setMyUncaughtException(myUncaughtExceptionhandler);
nlpworker.setUncaughtExceptionHandler(myUncaughtExceptionhandler);
nlpworker.start();
}
ZMQ.proxy(clients, workers, null);
}
}