Java Code Examples for org.zeromq.ZMQ#context()

The following examples show how to use org.zeromq.ZMQ#context() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Pull.java    From XRTB with Apache License 2.0 8 votes vote down vote up
public Pull(HttpServletResponse response, String port, String timeout, String limit) throws Exception {
	int lim = 1;
	if (limit != null) {
		lim = Integer.parseInt(limit);
	}
	ZMQ.Context context = ZMQ.context(1);
	ZMQ.Socket rcv = context.socket(ZMQ.PULL);
	rcv.bind("tcp://*:" + port);
	if (timeout != null) {
		int t = Integer.parseInt(timeout);
		rcv.setReceiveTimeOut(t);
	}
	
	int k = 0;
	while(k < lim || lim == 0) {
		String str = rcv.recvStr();		
		response.getWriter().println(str);
		k++;
	}
	
	rcv.close();
	context.term();
}
 
Example 2
Source File: Publisher.java    From XRTB with Apache License 2.0 6 votes vote down vote up
public Publisher(String binding, String topicName) throws Exception {

		mapper.setSerializationInclusion(Include.NON_NULL);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		
		context = ZMQ.context(1);
		publisher = context.socket(ZMQ.PUB);
		publisher.bind(binding);

		Thread.sleep(100);
		//System.out.println("Starting Publisher..");
		publisher.setIdentity("B".getBytes());
		publisher.setLinger(5000);
		publisher.setHWM(0);

		this.topicName = topicName;
	}
 
Example 3
Source File: WebMQPublisher.java    From bidder with Apache License 2.0 6 votes vote down vote up
public WebMQPublisher(String port, String topic, String message) throws Exception {

		String binding = "tcp://*:" + port;
		context = ZMQ.context(1);
		publisher = context.socket(ZMQ.PUB);
		publisher.bind(binding);
		Thread.sleep(1000);
		publisher.setIdentity("B".getBytes());
		publisher.setLinger(5000);
		publisher.setHWM(0);

		publisher.sendMore(topic);
		boolean isSent = publisher.send(message);
		publisher.close();
		context.term();
	}
 
Example 4
Source File: XPublisher.java    From bidder with Apache License 2.0 6 votes vote down vote up
public XPublisher(String binding, String topicName) throws Exception {
    super();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    context = ZMQ.context(1);
    publisher = context.socket(ZMQ.XPUB);
    publisher.bind(binding);

    Thread.sleep(100);
    //System.out.println("Starting Publisher..");
    publisher.setIdentity("B".getBytes());
    publisher.setLinger(5000);
    publisher.setHWM(0);

    this.topicName = topicName;
}
 
Example 5
Source File: ZeroMQBroker.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 6
Source File: WebMQPublisher.java    From XRTB with Apache License 2.0 6 votes vote down vote up
public WebMQPublisher(String port, String topic, String message) throws Exception {

		String binding = "tcp://*:" + port;
		context = ZMQ.context(1);
		publisher = context.socket(ZMQ.PUB);
		publisher.bind(binding);
		Thread.sleep(1000);
		publisher.setIdentity("B".getBytes());
		publisher.setLinger(5000);
		publisher.setHWM(0);

		publisher.sendMore(topic);
		boolean isSent = publisher.send(message);
		publisher.close();
		context.term();
	}
 
Example 7
Source File: TestAsyncMicroServiceMain.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 8
Source File: TrackerServer.java    From barefoot with Apache License 2.0 5 votes vote down vote up
public StatePublisher(int port) {
    context = ZMQ.context(1);
    socket = context.socket(ZMQ.PUB);
    socket.bind("tcp://*:" + port);
    this.setDaemon(true);
    this.start();
}
 
Example 9
Source File: RTopic.java    From XRTB with Apache License 2.0 5 votes vote down vote up
/**
 * A Topic handler with no publishing (just subscribes)
 * @param binding String.  The binding for the 
 * @param addresses List. My TCP address and topics for listening.
 * @throws Exception
 */
public RTopic(List<String> addresses) throws Exception {
	mapper.setSerializationInclusion(Include.NON_NULL);
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	
	context = ZMQ.context(1);	
	subscriber = new MSubscriber(this,addresses);
}
 
Example 10
Source File: AbstractBaseZeroMQInputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(OperatorContext ctx)
{
  context = ZMQ.context(1);
  subscriber = context.socket(ZMQ.SUB);
  subscriber.connect(url);
  subscriber.subscribe(filter.getBytes());
  syncclient = context.socket(ZMQ.REQ);
  syncclient.connect(syncUrl);
  syncclient.send("".getBytes(), 0);
}
 
Example 11
Source File: AsyncBankServiceImpl.java    From ignite-book-code-samples with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(ServiceContext serviceContext) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    Context context = ZMQ.context(1);

    //  Socket to talk to server
    Socket responder = context.socket(ZMQ.REP);
    responder.connect(zeroMqBrokerAddress);
    ZMQ.PollItem items[] = {new ZMQ.PollItem(responder, ZMQ.Poller.POLLIN)};
    while (!Thread.currentThread().isInterrupted() && !serviceContext.isCancelled()) {
        //  Wait for next request from client
        int rc = ZMQ.poll(items, 1000);
        if (rc == -1) {
            continue;
        }

        if (items[0].isReadable()) {
            String reqStr = responder.recvStr(0);
            System.out.printf("Received request: [%s]\n", reqStr);

            ValidateRequest req = objectMapper.readValue(reqStr, ValidateRequest.class);

            ValidateResponse result = validateOperation(req.getAccount(), req.getSum());
            System.out.printf("send response request: [%s]\n", result);

            responder.send(objectMapper.writeValueAsString(result));
        }
    }
    System.out.println("Stop async read!");

    //  We never get here but clean up anyhow
    responder.close();
    context.term();

}
 
Example 12
Source File: ContractEvent001.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test(enabled = true, description = "Subscribe event client")
public void testCpuCostDetail() {
  ZMQ.Context context = ZMQ.context(1);
  ZMQ.Socket req = context.socket(ZMQ.SUB);

  req.subscribe("blockTrigger");
  req.subscribe("transactionTrigger");
  req.subscribe("contractLogTrigger");
  req.subscribe("contractEventTrigger");
  req.monitor("inproc://reqmoniter", ZMQ.EVENT_CONNECTED | ZMQ.EVENT_DISCONNECTED);
  final ZMQ.Socket moniter = context.socket(ZMQ.PAIR);
  moniter.connect("inproc://reqmoniter");
  new Thread(new Runnable() {
    public void run() {
      while (true) {
        Event event = Event.read(moniter.base());
        System.out.println(event.event +  "  " + event.addr);
      }
    }

  }).start();
  req.connect("tcp://47.94.197.215:55555");
  req.setReceiveTimeOut(10000);

  while (true) {
    byte[] message = req.recv();
    if (message != null) {
      System.out.println("receive : " + new String(message));
    }
  }



}
 
Example 13
Source File: RTopic.java    From bidder with Apache License 2.0 5 votes vote down vote up
public RTopic(String address) throws Exception {
	context = ZMQ.context(1);
	
	mapper.setSerializationInclusion(Include.NON_NULL);
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	
	if (address.contains("kafka")==false && address.contains("&")) {
		String [] parts = address.split("&");
		subscriber = new Subscriber(this,parts[0]);
		topicName = parts[1];
		subscriber.subscribe(parts[1]);
	} else
		subscriber = new Subscriber(this,address);
}
 
Example 14
Source File: PushPull.java    From XRTB with Apache License 2.0 5 votes vote down vote up
public void pull() {
	Runnable redisupdater = () -> {
		ZMQ.Context context = ZMQ.context(1);
		ZMQ.Socket rcv = context.socket(ZMQ.PULL);
		rcv.bind("tcp://*:8086");
		rcv.setReceiveTimeOut(1000);
		String str = rcv.recvStr();
		System.out.println("Received: " + str);
		rcv.close();
		context.term();
	};
	Thread nthread = new Thread(redisupdater);
	nthread.start();
}
 
Example 15
Source File: PushPull.java    From bidder with Apache License 2.0 5 votes vote down vote up
public void push() {
	ZMQ.Context context = ZMQ.context(1);
	ZMQ.Socket sender = context.socket(ZMQ.PUSH);
	sender.connect("tcp://localhost:8086");
	sender.send("MESSAGE");
	sender.close();
	context.term();
}
 
Example 16
Source File: KernelSocketsZMQ.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public KernelSocketsZMQ(KernelFunctionality kernel, Config configuration, SocketCloseAction closeAction) {
  this.closeAction = closeAction;
  this.kernel = kernel;
  this.hmac = new HashedMessageAuthenticationCode(configuration.getKey());
  this.context = ZMQ.context(1);
  configureSockets(configuration);
}
 
Example 17
Source File: ZMQListener.java    From qupla with Apache License 2.0 5 votes vote down vote up
public ZMQListener(String address, int timeoutTolerance)
{
  this.address = address;
  this.timeoutTolerance = timeoutTolerance;
  ZMQ.Context context = ZMQ.context(1);
  socket = context.socket(ZMQ.SUB);
  socket.setReceiveTimeOut(timeoutTolerance);
}
 
Example 18
Source File: ProtocolProcessor.java    From aion with MIT License 4 votes vote down vote up
@Override
public void run() {
    LOG.info("Starting Aion Api Server <port={}>", cfgApi.getPort());
    String bindAddr = "tcp://" + cfgApi.getIp() + ":" + cfgApi.getPort();
    int msgTh = 5;

    try {
        // create context.
        Context ctx = ZMQ.context(1);

        // create router sock.
        Socket feSock = ctx.socket(ROUTER);
        if (cfgApi.isSecureConnectEnabledEnabled()) {
            // Currently the system will only load the first pair of the key files.
            loadCurveKeyPair();

            if (curveSecKey != null && curvePubKey != null) {
                feSock.setZAPDomain("global".getBytes());
                feSock.setCurveServer(true);
                feSock.setCurvePublicKey(curvePubKey);
                feSock.setCurveSecretKey(curveSecKey);
                LOG.info("Secure connection enabled!");
            } else {
                LOG.info(
                        "Can't find the keyfile for setup the connection. Secure connection disabled!");
            }
        } else {
            LOG.info("Secure connection disabled!");
        }

        feSock.setSndHWM(zmqHWM);
        feSock.bind(bindAddr);

        Socket wkSocks = ctx.socket(DEALER);
        wkSocks.bind(AION_ZMQ_WK_TH);

        Socket cbSock = ctx.socket(DEALER);
        cbSock.bind(AION_ZMQ_CB_TH);

        Socket evSock = ctx.socket(DEALER);
        evSock.bind(AION_ZMQ_EV_TH);

        Socket hbSock = ctx.socket(DEALER);
        hbSock.bind(AION_ZMQ_HB_TH);

        ExecutorService es = Executors.newFixedThreadPool(msgTh);
        es.execute(() -> callbackRun(ctx));
        es.execute(this::txWaitRun);
        es.execute(() -> eventRun(ctx));
        es.execute(() -> workerRun(ctx));
        es.execute(() -> hbRun(ctx));

        Proxy.proxy(feSock, wkSocks, cbSock, evSock, hbSock);

        if (LOG.isInfoEnabled()) {
            LOG.info("ProtocolProcessor.run thread finish.");
        }

        if (LOG.isInfoEnabled()) {
            LOG.info("Shutting down Zmq sockets...");
        }
        // Shutdown HdlrZmq
        ((HdlrZmq) handler).shutdown();
        // Shutdown ZmqSocket
        feSock.close();
        wkSocks.close();
        cbSock.close();
        evSock.close();
        hbSock.close();
        // Shutdown ExecutorService
        es.shutdown();

        ctx.close();
        if (LOG.isInfoEnabled()) {
            LOG.info("Shutdown Zmq sockets... Done!");
        }

    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("ProtocolProcessor.run exception: " + e.getMessage());
        }
    }
}
 
Example 19
Source File: Zerospike.java    From bidder with Apache License 2.0 4 votes vote down vote up
/**
 * Create the Cross pub/sub service.
 * @param pub int. The publisher port.
 * @param sub int. The subscriber port.
 * @throws Exception on 0MQ errors.
 */
public Zerospike(int sub, int pub, int listen, String fileName, String kafka, boolean trace, int ct) throws Exception {

    this.trace = trace;
    setInstance();

    context = ZMQ.context(ct);

    subscriber = context.socket(ZMQ.XSUB);
    subscriber.bind("tcp://*:" + sub);
    subscriber.setHWM(1000000);

    publisher = context.socket(ZMQ.XPUB);
    publisher.bind("tcp://*:" + pub);
    publisher.setHWM(1000000);

    // Uncomment this to receive info from the connections
    int anyPort = Utils.findOpenPort();
    ;
    listener = context.socket(ZMQ.PAIR);
    listener.connect("tcp://localhost:" + anyPort);
    listener.setHWM(1000000);

    this.trace = trace;
    try {
        if (kafka != null) {
            kafkaLogger = new ZPublisher(kafka);
        }
        db = DBMaker.fileDB(fileName)
                .fileMmapEnable()            // Always enable mmap
                .fileMmapEnableIfSupported() // Only enable mmap on supported platforms
                .fileMmapPreclearDisable()   // Make mmap file faster
                // Unmap (release resources) file when its closed.
                // That can cause JVM crash if file is accessed after it was unmapped
                // (there is possible race condition).
                .cleanerHackEnable()
                .transactionEnable()
                .make();
        objects = db.hashMap("objects").createOrOpen();
    } catch (Exception error) {
        error.printStackTrace();
        System.exit(1);
    }

    if (objects == null) {
        objects = db.hashMap("objects").create();
        logger.warn("Had to create initial objects.");
    }

    worker = new KeyDeletionScheduler(objects, logger);
    worker.setTrace(trace);

    spy = new ListenToZeroMQ(anyPort, objects, worker, trace);

    initializeLoad();

    AddShutdownHook hook = new AddShutdownHook();
    hook.attachShutDownHook(this);

    ScheduledExecutorService execService = Executors.newScheduledThreadPool(5);
    execService.scheduleAtFixedRate(() -> {
        try {
            printStatus();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }, 1, 1, TimeUnit.MINUTES);
    logger.info("*** System starting: publisher is at {}, subscriber is at {}, xfr is at {}", pub, sub, listen);
    if (kafkaLogger != null) {
        kafkaLogger.add("System starting: publisher is at " + pub + " subscriber is at " + sub);
    }
    new FileServer(logger, objects, listen);
    me = new Thread(this);
    me.start();
}
 
Example 20
Source File: ZMQIntegrationTest.java    From netty-zmtp with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
  context = ZMQ.context(1);
}