本文整理匯總了Java中org.zeromq.ZMQ類的典型用法代碼示例。如果您正苦於以下問題:Java ZMQ類的具體用法?Java ZMQ怎麽用?Java ZMQ使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ZMQ類屬於org.zeromq包,在下文中一共展示了ZMQ類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: open
import org.zeromq.ZMQ; //導入依賴的package包/類
@Override
public void open(Configuration config) throws Exception {
super.open(config);
// Prepare our context and sockets
context = ZMQ.context(1);
// Socket facing clients
frontend = context.socket(ZMQ.PULL);
frontend.bind(zmqConnectionConfig.getUri());
RuntimeContext runtimeContext = getRuntimeContext();
if (runtimeContext instanceof StreamingRuntimeContext
&& ((StreamingRuntimeContext) runtimeContext).isCheckpointingEnabled()) {
autoAck = false;
// enables transaction mode
//channel.txSelect();
} else {
autoAck = true;
}
LOG.debug("Starting ZeroMQ source with autoAck status: " + autoAck);
LOG.debug("Starting ZeroMQ source with uri: " + zmqConnectionConfig.getUri());
//channel.basicConsume(queueName, autoAck, consumer);
running = true;
}
示例2: ZMQProtobufClient
import org.zeromq.ZMQ; //導入依賴的package包/類
ZMQProtobufClient(String zurl) {
System.out.println("Starting zmq client to " + zurl);
ctx = new ZContext();
// We use ROUTER rather than DEALER because we want ZMQ to drop packets
// (rather than blocking)
// if we are not connected to the server.
socket = ctx.createSocket(ZMQ.ROUTER);
socket.setHWM(20);
socket.setLinger(200); // in msecs
// Use the following to get better client ids (must be unique)
String identity = UUID.randomUUID().toString();
socket.setIdentity(identity.getBytes(ZMQ.CHARSET));
socket.connect(zurl);
items = new PollItem[] { new PollItem(socket, Poller.POLLIN) };
}
示例3: sendMsg
import org.zeromq.ZMQ; //導入依賴的package包/類
private synchronized void sendMsg(ZMQ.Socket socket, Message message) {
String header = toJson(message.getHeader());
String parent = toJson(message.getParentHeader());
String meta = toJson(message.getMetadata());
String content = toJson(message.getContent());
String digest = hmac.sign(Arrays.asList(header, parent, meta, content));
ZMsg newZmsg = new ZMsg();
message.getIdentities().forEach(newZmsg::add);
newZmsg.add(DELIM);
newZmsg.add(digest.getBytes());
newZmsg.add(header.getBytes());
newZmsg.add(parent.getBytes());
newZmsg.add(meta.getBytes());
newZmsg.add(content.getBytes());
newZmsg.send(socket);
}
示例4: start
import org.zeromq.ZMQ; //導入依賴的package包/類
@Override
public void start() {
System.out.println("[Worker] Starting in " + Thread.currentThread().getName());
context = ZMQ.context(1);
subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://127.0.0.1:8001");
subscriber.connect("tcp://127.0.0.1:8002");
System.out.println("subscriber connected to ports 8001 & 8002");
System.out.println("receiving messages...");
// no filtering
subscriber.subscribe(ZMQ.SUBSCRIPTION_ALL); // no filtering
vertx.setPeriodic(1, v -> {
message = subscriber.recvStr(0).trim();
String[] result = message.split(" ");
System.out.println("exchange: " + result[0] + ", update: " + result[1]);
});
}
示例5: main
import org.zeromq.ZMQ; //導入依賴的package包/類
public static void main(String[] args) {
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://127.0.0.1:8001");
subscriber.connect("tcp://127.0.0.1:8002");
System.out.println("subscriber connected to ports 8001 & 8002");
System.out.println("receiving messages...");
// no filtering
subscriber.subscribe(ZMQ.SUBSCRIPTION_ALL); // no filtering
int numOfMessages = 1000;
String message;
for (int i = 0; i < numOfMessages; i++) {
message = subscriber.recvStr(0).trim();
String[] result = message.split(" ");
System.out.println("exchange: " + result[0] + ", update: " + result[1]);
}
subscriber.close();
context.term();
}
示例6: login
import org.zeromq.ZMQ; //導入依賴的package包/類
@Override
public void login(String server, int port, String name) {
try {
context = ZMQ.context(2);
subscriber = context.socket(ZMQ.SUB);
client = context.socket(ZMQ.REQ);
subscriber.setRcvHWM(0);
subscriber.connect(TCP_PREFIX + server + SEMICOLON + (port + 1));
subscriber.subscribe("".getBytes());
client.connect(TCP_PREFIX + server + SEMICOLON + port);
running.set(true);
executorService.submit(this::handleIncomingMessages);
client.send(objectMapper.writeValueAsBytes(loginCommand(name)));
client.recv(0);
} catch (Exception e) {
LOG.error(UNEXPECTED_ERROR, e);
throw new IllegalStateException(e);
}
}
示例7: connectToZMQ
import org.zeromq.ZMQ; //導入依賴的package包/類
/**
*
*/
private boolean connectToZMQ() {
connectionString = "tcp://" + ip + ":" + rpcPort;
try {
context = ZMQ.context(1);
setRequester(context.socket(ZMQ.REQ));
getRequester().setReceiveTimeOut(3000);
getRequester().connect(connectionString);
LogsController.getInstance().appendText(LogType.INFO, "Connecting to TRex:" + connectionString);
} catch (Exception ex) {
LOG.error("Invalid hostname", ex);
return false;
}
return true;
}
示例8: sendAsync
import org.zeromq.ZMQ; //導入依賴的package包/類
private static void sendAsync(int val, String account) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Context context = ZMQ.context(1);
// Socket to talk to server
Socket requester = context.socket(ZMQ.REQ);
requester.connect("tcp://localhost:5559");
System.out.println("launch and connect client.");
ValidateRequest req = new ValidateRequest(account, new BigDecimal(val));
//send request
requester.send(objectMapper.writeValueAsString(req), 0);
//receive response
String responseStr = requester.recvStr(0);
//parse and print reply
ValidateResponse reply = objectMapper.readValue(responseStr, ValidateResponse.class);
System.out.println("Received reply for request= " + req + " reply= " + reply + "");
// We never get here but clean up anyhow
requester.close();
context.term();
}
示例9: main
import org.zeromq.ZMQ; //導入依賴的package包/類
public static void main (String[] args) {
// Prepare our context and sockets
Context context = ZMQ.context(1);
// Socket facing clients
Socket frontend = context.socket(ZMQ.ROUTER);
frontend.bind("tcp://*:5559");
// Socket facing services
Socket backend = context.socket(ZMQ.DEALER);
backend.bind("tcp://*:5560");
// Start the proxy
ZMQ.proxy (frontend, backend, null);
// We never get here but clean up anyhow
frontend.close();
backend.close();
context.term();
}
示例10: doInBackground
import org.zeromq.ZMQ; //導入依賴的package包/類
@Override
protected Void doInBackground(Void... voids) {
try {
if(config_context==null||config_socket==null){
config_context = ZMQ.context(1);
config_socket = config_context.socket(ZMQ.PUSH);
config_socket.connect(target.getBaseport());
}
if(VERBOSE)Log.i(TAG,"sending configuration to "+target.getBaseport());
config_socket.send(config.build().toByteArray());
} catch (Exception e) {
if(DEBUG)Log.e(TAG,"ZeroMQConfig crash: "+e.getMessage());
e.printStackTrace();
}
return null;
}
示例11: sendMessage
import org.zeromq.ZMQ; //導入依賴的package包/類
public void sendMessage(byte[][] parts) throws IOException {
for (int i = 0; i < parts.length; i++) {
requester.send(parts[i], i < parts.length - 1 ? zmq.ZMQ.ZMQ_SNDMORE : 0);
}
int part = 0;
byte[] part1 = new byte[0];
byte[] part2 = new byte[0];
while (this.listen) {
part++;
if (part == 1) {
part1 = requester.recv();
} else if (part == 2 && requester.hasReceiveMore()) {
part2 = requester.recv();
}
if (!requester.hasReceiveMore()) {
part = 0;
if (this.listener != null) {
this.listener.onReply(part1, part2);
}
this.listen = false;
}
}
}
示例12: receive
import org.zeromq.ZMQ; //導入依賴的package包/類
/**
* Block until a message can be read
*
* @return
* @throws IOException
*/
public Envelope receive(long timeout) throws IOException {
ZMQ.poll(items, timeout);
if (items[0].isReadable()) {
// System.out.println("Receiving");
// The DEALER socket gives us the address envelope and message
ZMsg msg = ZMsg.recvMsg(socket);
// System.out.println("Recvd " + msg);
ZFrame content = msg.getLast();
assert (content != null);
// System.out.println("Content " + content);
return Envelope.parseFrom(content.getData());
} else
return null; // timed out
}
示例13: ZeroMQThread
import org.zeromq.ZMQ; //導入依賴的package包/類
/**
* Constructor.
*
* @param mgr Network manager for this server.
*/
ZeroMQThread(NetworkManager mgr) {
super("Elko ZeroMQ");
myNetworkManager = mgr;
myQueue = new Queue();
myConnections = new HashMap<ZMQ.Socket, ZeroMQConnection>();
myContext = ZMQ.context(1);
myPoller = myContext.poller();
mySignalRecvSocket = myContext.socket(ZMQ.PAIR);
mySignalRecvSocket.bind(ZMQ_SIGNAL_ADDR);
mySignalRecvSocketIndex =
myPoller.register(mySignalRecvSocket, ZMQ.Poller.POLLIN);
mySignalSendSocket = myContext.socket(ZMQ.PAIR);
mySignalSendSocket.connect(ZMQ_SIGNAL_ADDR);
start();
}
示例14: ZeroMQConnection
import org.zeromq.ZMQ; //導入依賴的package包/類
ZeroMQConnection(MessageHandlerFactory handlerFactory,
ByteIOFramerFactory framerFactory,
ZMQ.Socket socket,
boolean isSendMode,
ZeroMQThread thread,
NetworkManager networkMgr,
String remoteAddr)
{
super(networkMgr);
wakeupThreadForWrite();
mySocket = socket;
myMgr = networkMgr;
amOpen = true;
amSendMode = isSendMode;
myRemoteAddr = remoteAddr;
myFramer = framerFactory.provideFramer(this, label());
myOutputQueue = new Queue();
myThread = thread;
enqueueHandlerFactory(handlerFactory);
if (Trace.comm.event && Trace.ON) {
Trace.comm.eventm(this + " new ZMQ connection with " + remoteAddr);
}
}
示例15: run
import org.zeromq.ZMQ; //導入依賴的package包/類
@Override
public void run()
{
logger.debug("receiver running");
while (!Thread.currentThread().isInterrupted() && !shutDown) {
byte[] msg = subscriber.recv(ZMQ.NOBLOCK);
// convert to HashMap and save the values for each key
// then expect c to be 1000, b=20, a=2
// and do count++ (where count now would be 30)
if (msg == null || msg.length == 0) {
continue;
}
String str = new String(msg);
if (str.indexOf("{") == -1) {
continue;
}
int eq = str.indexOf('=');
String key = str.substring(1, eq);
int value = Integer.parseInt(str.substring(eq + 1, str.length() - 1));
logger.debug("\nsubscriber recv: {}", str);
dataMap.put(key, value);
count++;
logger.debug("out of loop.. ");
}
}