先可以构建一个Socket池,方便调用
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;
public class ZMQUtils {
private static final Context context = ZMQ.context(1); // 创建一个I/O线程的上下文private static final int DEFAULT_POOL_SIZE = 5;// 默认池大小
private static final Queue<Socket> pool;// 池
static {
pool = new ArrayBlockingQueue<Socket>(DEFAULT_POOL_SIZE);
}
/**
* 获取zmq的socket(req)
*
* @return
*/
public static Socket getZMQSocket() {
Socket socket = pool.poll();
if (socket == null) {
socket = context.socket(ZMQ.REQ);// 创建一个request类型的socket,这里可以将其简单的理解为客户端,用于向response端发送数据
}
return socket;
}
/**
* 将zmq的socket(req)归还池()
*
* @param socket
*/
public static void releaseZMQSocket(Socket socket) {
if (socket != null) {
if (!pool.offer(socket)) {
socket.close();
}
}
}
}
通讯调用实例代码如下:
Map<String, Object> map = new HashMap<>();
map.put("id", arrayList);
JSONObject requJson = new JSONObject();
requJson.put("importpcap", map);
String request = requJson.toString();
Socket socket = ZMQUtils.getZMQSocket();
try {
socket.setReceiveTimeOut(5000);
socket.connect("tcp://" + decodeIp + ":" + decodePort); // 与response端建立连接
socket.send(request.getBytes()); // 向reponse端发送数据
byte[] responseBytes = socket.recv(); // 接收response发送回来的数据
if (null == responseBytes) {
throw new ApplicationException("后台通信异常!");
} else {
ZMQUtils.releaseZMQSocket(socket);
Integer result = null;
String response = new String(responseBytes, "UTF8");
JSONObject respJson = JSONObject.fromObject(response);
if (null != respJson) {
JSONObject conftestplan = respJson
.getJSONObject("importpcap");
if (null != conftestplan) {
result = conftestplan.getInt("result");
// System.out.println(result);
}
}
if (null == result) {
throw new ApplicationException("后台通信异常!");
} else {
switch (result) {
case 0:
// 通信成功清空缓存ID
context.setAttribute("importpcapIds", null);
System.out.println("推送完毕!!!!");
break;
default:
break;
}
}
}
} catch (Exception e) {
if (e instanceof ApplicationException) {
// throw new ApplicationException(e.getMessage());
context.setAttribute("importpcapIds", null);
System.out.println(e.getMessage());
} else {
socket.close();
// throw new ApplicationException("后台通信异常!");
context.setAttribute("importpcapIds", null);
System.out.println("后台通信异常!");
}
}