List of usage examples for com.rabbitmq.client DefaultConsumer DefaultConsumer
public DefaultConsumer(Channel channel)
From source file:stock84885customer.CustomerQueryController.java
private void initQueryResultChannel() throws IOException { queryResultChannel = connection.createChannel(); queryResultChannel.exchangeDeclare(queryResultsExchangeName, "direct"); queryResultsQueueName = queryResultChannel.queueDeclare().getQueue(); queryResultChannel.queueBind(queryResultsQueueName, queryResultsExchangeName, name); queryResultsConsumer = new DefaultConsumer(queryResultChannel) { @Override//from w w w. j a v a 2s. co m public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try { String result = new String(body, "UTF-8"); logger.trace(name + " received query result: " + result); releaseNetworkResources(); } catch (Exception ex) { logger.error(ex.toString()); } } }; }
From source file:stock84885orderreceiver.OrderReceiverController.java
public void run() throws IOException, TimeoutException { try {/*ww w . j av a2s .c om*/ connFactory = new ConnectionFactory(); connFactory.setHost(hostName); connection = connFactory.newConnection(); ordersChannel = connection.createChannel(); resultsChannel = connection.createChannel(); shippingChannel = connection.createChannel(); ordersChannel.queueDeclare(ordersExchangeName, true, //Passive declaration false, //Non-durable queue false, //Non-exclusive queue null //No arguments ); resultsChannel.exchangeDeclare(resultsExchangeName, "direct"); shippingChannel.queueDeclare(shippingExchangeName, true, //Passive declaration false, //Non-durable queue false, //Non-exclusive queue null //No arguments ); traceLogger.trace(name + " waiting for orders"); ordersChannel.basicQos(1); final Consumer consumer = new DefaultConsumer(ordersChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Order order = Order.deserialize(body); try { processOrder(order); } catch (InterruptedException | TimeoutException ex) { traceLogger.error(ex.toString()); } finally { ordersChannel.basicAck(envelope.getDeliveryTag(), false); } } }; ordersChannel.basicConsume(ordersExchangeName, false, consumer); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { releaseNetworkResources(); } catch (IOException | TimeoutException ex) { try { traceLogger.error(ex.toString()); } catch (IOException ex1) { System.err.println(ex1.toString()); } } } }); } catch (IOException | TimeoutException e) { releaseNetworkResources(); throw e; } }
From source file:stock84885queryhandler.QueryHandlerController.java
public void run() throws IOException, TimeoutException { try {/*from w ww. ja va 2s . c o m*/ connFactory = new ConnectionFactory(); connFactory.setHost(hostName); connection = connFactory.newConnection(); queriesChannel = connection.createChannel(); queriesResultsChannel = connection.createChannel(); queriesChannel.queueDeclare(queriesExchangeName, true, //Passive declaration false, //Non-durable queue false, //Non-exclusive queue null //No arguments ); queriesResultsChannel.exchangeDeclare(queriesResultsExchangeName, "direct"); logger.trace(name + " waiting for queries..."); queriesChannel.basicQos(1); final Consumer consumer = new DefaultConsumer(queriesChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String userName = new String(body, "UTF-8"); try { processQuery(userName); } catch (Exception ex) { logger.error(ex.toString()); } finally { queriesChannel.basicAck(envelope.getDeliveryTag(), false); } } }; queriesChannel.basicConsume(queriesExchangeName, false, consumer); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { releaseNetworkResources(); } catch (IOException | TimeoutException ex) { try { logger.error(ex.toString()); } catch (IOException ex1) { System.err.println(ex1.toString()); } } } }); } catch (IOException | TimeoutException e) { releaseNetworkResources(); throw e; } }
From source file:stock84885shipping.ShippingController.java
public void run() throws URISyntaxException, IOException, TimeoutException { try {// w w w . j a v a 2 s .c o m connFactory = new ConnectionFactory(); connFactory.setHost(hostName); connection = connFactory.newConnection(); shippingChannel = connection.createChannel(); deliveryChannel = connection.createChannel(); shippingChannel.queueDeclare(shippingExchangeName, true, //Passive declaration false, //Non-durable queue false, //Non-exclusive queue null //No arguments ); deliveryChannel.exchangeDeclare(deliveryExchangeName, "direct"); logger.trace(name + " waiting for orders"); shippingChannel.basicQos(1); final Consumer consumer = new DefaultConsumer(shippingChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Order order = Order.deserialize(body); logger.trace(name + " received order " + order.getID()); try { deliverOrder(order); } catch (Exception ex) { logger.error(ex.toString()); } } }; shippingChannel.basicConsume(shippingExchangeName, false, consumer); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { releaseNetworkResources(); } catch (IOException | TimeoutException ex) { try { logger.error(ex.toString()); } catch (IOException ex1) { System.err.println(ex1.toString()); } } } }); } catch (IOException | TimeoutException e) { releaseNetworkResources(); throw e; } }
From source file:tracer.manager.Manager.java
License:Apache License
public void connectToRabbitNode() { try {/* ww w.j ava2s . com*/ com.rabbitmq.client.ConnectionFactory myFactory = new ConnectionFactory(); myFactory.setHost(HOST); myFactory.setPort(PORT); myFactory.setUsername(USER_NAME); myFactory.setPassword(PASSWORD); myFactory.setVirtualHost(VIRTUAL_HOST_NAME); myFactory.setConnectionTimeout(TIMEOUT); //Automatic recovery from network failures myFactory.setAutomaticRecoveryEnabled(true); System.out.println("automatic recovery from network failures is " + "enabled"); System.out.println("creating new connection.."); myConnection = myFactory.newConnection(); System.out.println("host: " + HOST + " is connected.."); System.out.println("creating new channel.."); myChannel = myConnection.createChannel(); System.out.println("declaring new Exchange.."); switch (getExchageParams()) { case 0: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, false, false, null); break; case 1: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, false, null); break; case 2: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, true, false, null); break; case 3: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, false, true, null); break; case 4: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, true, false, null); break; case 5: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, true, null); break; case 6: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, true, true, null); break; case 7: myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, true, true, null); break; default: break; } System.out.println("creating random queue.."); String QUEUE_NAME = myChannel.queueDeclare().getQueue(); for (String bindingKey : BINDING_KEYS) { System.out.println("binding to exchange=" + EXCHANGE_NAME + " using Binding Key=" + bindingKey); myChannel.queueBind(QUEUE_NAME, EXCHANGE_NAME, bindingKey); } System.out.println("waiting for messages, this may take few seconds" + ".."); System.out.println(" - rk: routing key"); System.out.println(" - en: exchange name"); System.out.println(" - ts: time stamp"); System.out.println(" - ct: content type"); System.out.println(" - ce: content encoding"); System.out.println(" - mp: message preview"); myStatsUpdater.start(); com.rabbitmq.client.Consumer myConsumer = new DefaultConsumer(myChannel) { int messageCounter = 1; @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String messageCore = new String(body, "UTF-8"); String currentRoutingKey = envelope.getRoutingKey(); //currentRPC is used for display in the global tracing table String currentRPC = getRPCMethod(messageCore); //there are redendant RPCs. to make the difference, we add //the routing key to the RPC String currentRPCandRK = currentRoutingKey + " * " + currentRPC; addNewMessageToInbox(new Object[] { messageCounter, getFormattedTime(), EXCHANGE_NAME, envelope.getRoutingKey(), messageCore, properties }); //verify if it's a new or a deja-vu RPC in the main //rpc method tracking list if (!rpcMethodsList.contains(currentRPCandRK)) { rpcMethodsList.add(currentRPCandRK); } //verify if it's a new or a deja-vu routing key in the main //routing keys tracking list if (!routingKeysList.contains(currentRoutingKey)) { routingKeysList.add(currentRoutingKey); } //verify if it's a new or a deja-vu routing key in the stats //recording list and init stats //logically it can be added to the condition above but //I prefer it this way if (!myRKStatsCounterMap.containsKey(currentRoutingKey)) { myRKStatsCounterMap.put(currentRoutingKey, 1); myRKStatsPercentageMap.put(currentRoutingKey, (1.0f / messageCounter) * 100); myRKStatsFiveSecondsCounterMap.put(currentRoutingKey, 1); myRKStatsTotalDataSizeMap.put(currentRoutingKey, (body.length / 1024F)); myRKStatsMeanDataSizeMap.put(currentRoutingKey, (body.length / 1024F)); dynamicRKRates.add(1); } else { //FIXED: chaos.. update: everything is fine myRKStatsCounterMap.put(currentRoutingKey, myRKStatsCounterMap.get(currentRoutingKey) + 1); for (String rk : routingKeysList) { //loop all routing keys because it depends on the //total number of recieved messages. myRKStatsPercentageMap.put(rk, (((float) myRKStatsCounterMap.get(rk)) / messageCounter) * 100); } myRKStatsTotalDataSizeMap.put(currentRoutingKey, myRKStatsTotalDataSizeMap.get(currentRoutingKey) + (body.length / 1024.0F)); myRKStatsMeanDataSizeMap.put(currentRoutingKey, ((float) myRKStatsTotalDataSizeMap.get(currentRoutingKey)) / myRKStatsCounterMap.get(currentRoutingKey)); } //verify if it's a new or a deja-vu rpc in the stats //recording list and init stats if (!myRPCStatsCounterMap.containsKey(currentRPCandRK)) { myRPCStatsCounterMap.put(currentRPCandRK, 1); myRPCStatsPercentageMap.put(currentRPCandRK, (1.0f / messageCounter) * 100); myRPCRKExchangeMap.put(currentRPCandRK, new String[] { EXCHANGE_NAME, currentRoutingKey, currentRPC }); } else { myRPCStatsCounterMap.put(currentRPCandRK, myRPCStatsCounterMap.get(currentRPCandRK) + 1); for (String rpc : rpcMethodsList) { //loop all rpc because it depends on the //total number of received messages. //using the messageCounter is OK because even //messages that are not RPCs are considered as //RPCs with a 'N/A' RPC type. myRPCStatsPercentageMap.put(rpc, (((float) myRPCStatsCounterMap.get(rpc)) / messageCounter) * 100); } } // Properties object added to message object displayNewMessage(new Object[] { messageCounter, getFormattedTime(), EXCHANGE_NAME, envelope.getRoutingKey(), currentRPC, properties }); //FIXED: custom messages (ex. used for test) may be less //longer than 30 character which raises an exception. String messagePreview = messageCore; if (messageCore.length() > 100) { messagePreview = messageCore.substring(0, 85) + "..."; } System.out.println("MSG [" + messageCounter + "]:" + " | rk: " + envelope.getRoutingKey() + " | en: " + envelope.getExchange() + " | ts: " + properties.getTimestamp() + " | ct: " + properties.getContentType() + " | ce: " + properties.getContentEncoding() + " | mp: " + messagePreview + " |"); messageCounter++; } private String getFormattedTime() { return myDateFormatter.format(new Date()); } private String getRPCMethod(String messageCore) { String rpcMethodName = "N/A"; //clean up the message core messageCore = messageCore.replaceAll("[\\p{Punct}&&[^,:_]]", ""); //transform the message core to a list of tokens StringTokenizer st1 = new StringTokenizer(messageCore, ","); //locate the string token 'method' and save the next //one which is the rpc method name while (st1.hasMoreElements()) { String token = (String) st1.nextElement(); if (token.trim().startsWith("method")) { rpcMethodName = token.substring(9); } } return rpcMethodName; } }; myChannel.basicConsume(QUEUE_NAME, true, myConsumer); } catch (IOException ex) { ex.printStackTrace(System.out); } catch (TimeoutException ex) { ex.printStackTrace(System.out); } }
From source file:tracer.ui.LoggerUI.java
License:Apache License
private void connectRMQNode(Object[] rmqNodeData) { try {/*from w w w . j av a 2 s . co m*/ com.rabbitmq.client.ConnectionFactory myFactory = new ConnectionFactory(); myFactory.setHost((String) rmqNodeData[0]); myFactory.setPort((Integer) rmqNodeData[1]); myFactory.setUsername((String) rmqNodeData[2]); myFactory.setPassword((String) rmqNodeData[3]); myFactory.setVirtualHost((String) rmqNodeData[4]); myFactory.setConnectionTimeout((Integer) rmqNodeData[5]); //Automatic recovery from network failures myFactory.setAutomaticRecoveryEnabled(true); System.out.println("automatic recovery from network failures is " + "enabled"); System.out.println("creating new connection.."); myConnection = myFactory.newConnection(); System.out.println("creating new channel.."); myChannel = myConnection.createChannel(); System.out.println("declaring the log exchange.."); myChannel.exchangeDeclare(LOG_EXCHANGE_NAME, LOG_EXCHANGE_TYPE, true, false, true, null); System.out.println("creating random queue.."); String QUEUE_NAME = myChannel.queueDeclare().getQueue(); System.out.println("binding to exchange=" + LOG_EXCHANGE_NAME + " using binding key=" + LOG_BK); myChannel.queueBind(QUEUE_NAME, LOG_EXCHANGE_NAME, LOG_BK); System.out.println("waiting for messages, this may take few seconds" + ".."); com.rabbitmq.client.Consumer myConsumer = new DefaultConsumer(myChannel) { int messageCounter = 1; @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String messageCore = new String(body, "UTF-8"); addNewMessageToInbox(new Object[] { messageCounter, getFormattedTime(), envelope.getRoutingKey(), messageCore }); // Properties object added to message object displayNewMessage(new Object[] { messageCounter, getFormattedTime(), envelope.getRoutingKey(), messageCore }); messageCounter++; } private String getFormattedTime() { return myDateFormatter.format(new Date()); } public void addNewMessageToInbox(Object[] message) { //inbox.add(message); } private void displayNewMessage(Object[] data) { DefaultTableModel logTableModel = (DefaultTableModel) logTable.getModel(); logTableModel.addRow(data); // for (int i = 0; i < data.length; i++) { // logTable.setValueAt(data[i], logTable.getRowCount()+1, // i); // } } }; myChannel.basicConsume(QUEUE_NAME, true, myConsumer); } catch (IOException ex) { ex.printStackTrace(System.out); } catch (TimeoutException ex) { ex.printStackTrace(System.out); } }
From source file:tugas4pat.RabbitMQClient.java
public RabbitMQClient() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(authHost);//w w w . j a v a2 s . com factory.setUsername(authUsername); factory.setPassword(authPassword); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_CHANNEL_NAME, "direct"); channel.exchangeDeclare(EXCHANGE_USER_NAME, "fanout"); queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, EXCHANGE_CHANNEL_NAME, ""); queueUser = channel.queueDeclare().getQueue(); channel.queueBind(queueUser, EXCHANGE_USER_NAME, ""); Consumer messageConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println("[x] Received '" + message + "'"); } }; channel.basicConsume(queueName, true, messageConsumer); Consumer userConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); switch (message.substring(0, 1)) { case "+": userList.add(message.substring(1)); System.out.println("Add " + message.substring(1) + " to list"); break; case "-": userList.remove(userList.indexOf(message.substring(1))); System.out.println("Remove " + message.substring(1) + " from list"); break; } System.out.println("[x] New user : '" + message.substring(1) + "'"); } }; channel.basicConsume(queueUser, true, userConsumer); }
From source file:tugas4pat.RabbitMQClient.java
public void join_channel(String _channel) throws IOException { try {//w ww. j ava2s.c om channelString = _channel; queueChannel = channel.queueDeclare().getQueue(); channel.queueBind(queueChannel, EXCHANGE_CHANNEL_NAME, _channel); Consumer channelConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(message); } }; channel.basicConsume(queueChannel, true, channelConsumer); channelList.add(_channel); channelToQueue.put(_channel, queueChannel); } finally { System.out.println("You have joined " + _channel); } }
From source file:uk.trainwatch.rabbitmq.RabbitRPCClient.java
License:Apache License
private DefaultConsumer setupConsumer() throws IOException { DefaultConsumer con = new DefaultConsumer(channel) { @Override/* w w w .ja v a 2s . c o m*/ public void handleShutdownSignal(String consumerTag, ShutdownSignalException signal) { continuationMap.values().forEach(c -> c.set(signal)); consumer = null; } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { continuationMap.computeIfPresent(properties.getCorrelationId(), (replyId, blocker) -> { blocker.set(body); return null; }); } }; channel.basicConsume(replyQueue, true, con); return con; }
From source file:user.Client.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("rabbitmq.akhfa.me"); factory.setUsername(username);// w ww .j ava2s . c o m factory.setPassword(password); factory.setVirtualHost("pat"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); ArrayList<String> daftarNick = getAllQueues(); String nick = ""; while (true) { Scanner in = new Scanner(System.in); System.out.print("Please enter your command: "); String command = in.nextLine(); String[] com = command.split(" ", 2); try { switch (com[0]) { case "/NICK": if (!nick.equals("")) { System.out.println("You have registered with nickname: " + nick); } else { if (!daftarNick.contains(com[1])) { channel.queueDeclare(com[1], false, false, true, null); nick = com[1]; System.out.println("Your nickname is " + nick); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); filterChannel(message); } }; channel.basicConsume(nick, true, consumer); } else { System.out.println("Nickname exists."); } } break; case "/JOIN": channel.exchangeDeclare(com[1], "fanout", false, false, false, null); channel.queueBind(nick, com[1], ""); System.out.println("You have successfully join " + com[1]); break; case "/LEAVE": channel.queueUnbind(nick, com[1], ""); System.out.println("Leave " + com[1]); break; case "/EXIT": System.out.println("bye bye... :D"); System.exit(0); default: String message = nick + ' ' + command; channel.basicPublish(com[0].substring(1), "", null, message.getBytes("UTF-8")); break; } } catch (Exception e) { if (command.compareTo("/NICK") == 0) { //random nick String random; if (!nick.equals("")) { System.out.println("You have registered with nickname: " + nick); } else { do { random = randomNick(); } while (daftarNick.contains(random)); nick = random; channel.queueDeclare(random, false, false, true, null); System.out.println("Your nickname is " + random); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); filterChannel(message); } }; channel.basicConsume(nick, true, consumer); } } else if ((command.compareTo("/JOIN") == 0) || (command.compareTo("/LEAVE") == 0)) { //error System.out.println("Please enter channel name!"); } else if (command.charAt(0) == '@') { System.out.println("Please enter your command for the channel."); } else { System.out.println("Invalid command."); } } } }