List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:com.mycompany.normalizer.Normalizer.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); final Channel sendingChannel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); sendingChannel.exchangeDeclare(SENDING_QUEUE_NAME, "fanout"); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override//from w w w . ja v a2 s.c o m 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 + "'"); //HANDLE HERE if (message.startsWith("{")) { // Transform with GSON schoolBank = message.contains("-"); if (!schoolBank) { message = message.replace("-", ""); JResponse jresponse = gson.fromJson(message, JResponse.class); jresponse.setBank("cphbusiness.bankJSON"); message = gson.toJson(jresponse); } else { message = message.replace("-", ""); JResponse jresponse = gson.fromJson(message, JResponse.class); jresponse.setBank("DreamTeamBankJSON"); message = gson.toJson(jresponse); } sendingChannel.basicPublish(SENDING_QUEUE_NAME, "", null, message.getBytes()); } else { schoolBank = message.contains("-"); String result = ""; if (!schoolBank) { message = message.replace("-", ""); JSONObject soapDatainJsonObject = XML.toJSONObject(message); result = gson.toJson(soapDatainJsonObject); result = result.replace("{\"map\":{\"LoanResponse\":{\"map\":", ""); result = result.replace("}}}", ""); JResponse jresponse = gson.fromJson(result, JResponse.class); jresponse.setBank("cphbusiness.bankXML"); result = gson.toJson(jresponse); } else { message = message.replace("-", ""); JSONObject soapDatainJsonObject = XML.toJSONObject(message); result = gson.toJson(soapDatainJsonObject); result = result.replace("{\"map\":{\"LoanResponse\":{\"map\":", ""); result = result.replace("}}}", ""); JResponse jresponse = gson.fromJson(result, JResponse.class); jresponse.setBank("DreamTeamBankXML"); result = gson.toJson(jresponse); } // XResponse response = gson.fromJson(soapDatainJsonObject, XResponse.class); sendingChannel.basicPublish(SENDING_QUEUE_NAME, "", null, result.getBytes()); } } }; channel.basicConsume(QUEUE_NAME, true, consumer); }
From source file:com.mycompany.receiptlist.ReceiptList.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel listeningChannel = connection.createChannel(); final Channel sendingChannel = connection.createChannel(); listeningChannel.queueDeclare(QUEUE_NAME, false, false, false, null); sendingChannel.exchangeDeclare(EXCHANGE_NAME, "direct"); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(listeningChannel) { @Override//from w ww . j a v a 2s. co m 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 + "'"); String[] arr = message.split(","); for (int i = 0; i < arr.length; i++) { switch (arr[i]) { case "DreamTeamXMLQueue": sendingChannel.basicPublish(EXCHANGE_NAME, "DreamTeamBankXML", null, message.getBytes()); break; case "DreamTeamJSONQueue": sendingChannel.basicPublish(EXCHANGE_NAME, "DreamTeamBankJSON", null, message.getBytes()); break; case "cphbusiness.bankXML": sendingChannel.basicPublish(EXCHANGE_NAME, "CphBusinessXML", null, message.getBytes()); break; case "cphbusiness.bankJSON": sendingChannel.basicPublish(EXCHANGE_NAME, "CphBusinessJSON", null, message.getBytes()); break; } } } }; listeningChannel.basicConsume(QUEUE_NAME, true, consumer); }
From source file:com.navercorp.pinpoint.plugin.jdk7.rabbitmq.RabbitMQTestRunner.java
License:Apache License
void runPushTest() throws Exception { final String message = "hello rabbit mq"; // producer side final Connection producerConnection = connectionFactory.newConnection(); final Channel producerChannel = producerConnection.createChannel(); producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false); producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null); producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PUSH, RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH); AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder(); producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH, false, false, builder.appId("test").build(), message.getBytes()); producerChannel.close();/*from w ww. j ava 2s. com*/ producerConnection.close(); //comsumer side final Connection consumerConnection = connectionFactory.newConnection(); final Channel consumerChannel = consumerConnection.createChannel(); final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":" + consumerConnection.getPort(); consumerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null); TestConsumer<String> consumer = new TestConsumer<String>(consumerChannel, MessageConverter.FOR_TEST); consumerChannel.basicConsume(RabbitMQTestConstants.QUEUE_PUSH, true, consumer); // wait consumer Assert.assertEquals(message, consumer.getMessage(10, TimeUnit.SECONDS)); consumerChannel.close(); consumerConnection.close(); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); // Wait till all traces are recorded (consumer traces are recorded from another thread) awaitAndVerifyTraceCount(verifier, 6, 5000L); verifier.printCache(); Class<?> producerChannelClass = producerChannel.getClass(); Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class); ExpectedTrace channelBasicPublishTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType channelBasicPublish, // method null, // rpc remoteAddress, // endPoint "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE), Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH)); ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType "RabbitMQ Consumer Invocation", // method "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip) remoteAddress, // remoteAddress Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH)); Class<?> consumerDispatchClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher"); Method consumerDispatchHandleDelivery = consumerDispatchClass.getDeclaredMethod("handleDelivery", Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class); ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations .event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, consumerDispatchHandleDelivery); // method ExpectedTrace asynchronousInvocationTrace = Expectations.event(ServiceType.ASYNC.getName(), "Asynchronous Invocation"); Class<?> consumerClass = consumer.getClass(); Method consumerHandleDelivery = consumerClass.getDeclaredMethod("handleDelivery", String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class); ExpectedTrace consumerHandleDeliveryTrace = Expectations .event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, consumerHandleDelivery); Class<?> propagationMarkerClass = PropagationMarker.class; Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark"); ExpectedTrace markTrace = Expectations.event(ServiceType.INTERNAL_METHOD.getName(), propagationMarkerMark); verifier.verifyTrace(channelBasicPublishTrace, rabbitMqConsumerInvocationTrace, consumerDispatcherHandleDeliveryTrace, asynchronousInvocationTrace, consumerHandleDeliveryTrace, markTrace); verifier.verifyTraceCount(0); }
From source file:com.navercorp.pinpoint.plugin.jdk7.rabbitmq.RabbitMQTestRunner.java
License:Apache License
void runPullTest() throws Exception { final String message = "hello rabbit mq"; // producer side final Connection producerConnection = connectionFactory.newConnection(); final Channel producerChannel = producerConnection.createChannel(); producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false); producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PULL, false, false, false, null); producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PULL, RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL); AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder(); producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL, false, false, builder.appId("test").build(), message.getBytes()); producerChannel.close();// w ww. j a va 2 s. c om producerConnection.close(); //comsumer side final Connection consumerConnection = connectionFactory.newConnection(); final Channel consumerChannel = consumerConnection.createChannel(); final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":" + consumerConnection.getPort(); TestMessagePuller messagePuller = new TestMessagePuller(consumerChannel); Assert.assertEquals(message, messagePuller.pullMessage(MessageConverter.FOR_TEST, RabbitMQTestConstants.QUEUE_PULL, true)); consumerChannel.close(); consumerConnection.close(); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); // Wait till all traces are recorded (consumer traces are recorded from another thread) awaitAndVerifyTraceCount(verifier, 5, 5000L); verifier.printCache(); // verify producer traces Class<?> producerChannelClass = producerChannel.getClass(); Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class); ExpectedTrace channelBasicPublishTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType channelBasicPublish, // method null, // rpc remoteAddress, // endPoint "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE), Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL)); ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType "RabbitMQ Consumer Invocation", // method "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip) remoteAddress, // remoteAddress Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL)); Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel"); Method handleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand", AMQCommand.class); ExpectedTrace handleCompleteInboundCommandTrace = Expectations.event( RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType handleCompleteInboundCommand); // method verifier.verifyDiscreteTrace(channelBasicPublishTrace, rabbitMqConsumerInvocationTrace, handleCompleteInboundCommandTrace); // verify consumer traces Class<?> consumerChannelClass = consumerChannel.getClass(); Method channelBasicGet = consumerChannelClass.getDeclaredMethod("basicGet", String.class, boolean.class); ExpectedTrace channelBasicGetTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, channelBasicGet); Class<?> propagationMarkerClass = PropagationMarker.class; Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark"); ExpectedTrace markTrace = Expectations.event(ServiceType.INTERNAL_METHOD.getName(), propagationMarkerMark); verifier.verifyDiscreteTrace(channelBasicGetTrace, markTrace); verifier.verifyTraceCount(0); }
From source file:com.nesscomputing.amqp.AbstractAmqpRunnable.java
License:Apache License
protected Channel channelConnect() throws IOException { Channel channel = channelHolder.get(); if (channel == null) { final Connection connection = connectionFactory.newConnection(); connectionHolder.set(connection); channel = connection.createChannel(); channelHolder.set(channel);/*from ww w. j a v a 2s.co m*/ connectCallback(channel); } return channel; }
From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java
/** * @param args the command line arguments * @throws java.lang.Exception// w ww . j a v a 2 s . c o m */ public static void main(String[] args) throws Exception { /** * Set properties at runtime */ System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log"); AppConstants.loadAppConfig(); final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getDlrReceiverExchangeName(); final String routingKey = GATEWAY_ID; Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class); try { Connection connection = AppConstants.getRabbitMqObject().newConnection(); connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { //throw new UnsupportedOperationException("Not supported yet."); if (cause.isHardError()) { Connection conn; conn = (Connection) cause.getReference(); if (!cause.isInitiatedByApplication()) { Method reason = cause.getReason(); logger.info("REASON:" + reason.toString()); } } else { Channel ch = (Channel) cause.getReference(); logger.info("NO HARDSHUTDOWN"); } } }); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); channel.basicQos(1000); //channel.addShutdownListener(listener); logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C"); Consumer consumer; consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Map<String, String> dataToPost = new HashMap<>(); String payload = new String(body, "UTF-8"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload); String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator()); for (String payloadPart : payloadParts) { String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator()); //check if any parameter is empty if (s.length == 2) { dataToPost.put(s[0], s[1]); } else { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]); dataToPost.put(s[0], null); } } long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall(dataToPost)) { channel.basicAck(deliveryTag, false); } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------"); dataToPost.clear(); payloadParts = null; } }; String cTag = channel.basicConsume(queueName, false, consumer); logger.info("CONSUMER TAG : " + cTag); } catch (IOException | TimeoutException e) { logger.error("RMQ_ERROR:" + e.getMessage()); } }
From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java
/** * @param args the command line arguments * @throws java.lang.Exception// w w w . j a va 2 s.c o m */ public static void main(String[] args) throws Exception { /** * Set properties at runtime */ System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log"); AppConstants.loadAppConfig(); final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getSmsReceiverExchangeName(); final String routingKey = GATEWAY_ID; Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class); try { Connection connection = AppConstants.getRabbitMqObject().newConnection(); connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { //throw new UnsupportedOperationException("Not supported yet."); if (cause.isHardError()) { Connection conn; conn = (Connection) cause.getReference(); if (!cause.isInitiatedByApplication()) { Method reason = cause.getReason(); logger.info("REASON:" + reason.toString()); } } else { Channel ch = (Channel) cause.getReference(); logger.info("NO HARDSHUTDOWN"); } } }); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); channel.basicQos(1000); //channel.addShutdownListener(listener); logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C"); Consumer consumer; consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Map<String, String> dataToPost = new HashMap<>(); String payload = new String(body, "UTF-8"); String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator()); for (String payloadPart : payloadParts) { String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator()); dataToPost.put(s[0], s[1]); } logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload); long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall(dataToPost)) { if (saveRequestData()) { channel.basicAck(deliveryTag, false); } else { channel.basicNack(deliveryTag, false, true); } } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------"); API_CALL_STATS.clear(); dataToPost.clear(); payloadParts = null; } }; String cTag = channel.basicConsume(queueName, false, consumer); logger.info("CONSUMER TAG : " + cTag); } catch (IOException | TimeoutException e) { logger.error("RMQ_ERROR:" + e.getMessage()); } }
From source file:com.nifi.processors.amqp.AMQPWorker.java
License:Apache License
/** * Creates an instance of this worker initializing it with AMQP * {@link Connection} and creating a target {@link Channel} used by * sub-classes to interact with AMQP-based messaging system. * * @param connection// www . java 2s . c om * instance of {@link Connection} */ public AMQPWorker(Connection connection) { this.validateConnection(connection); try { this.channel = connection.createChannel(); } catch (IOException e) { logger.error("Failed to create Channel for " + connection, e); throw new IllegalStateException(e); } }
From source file:com.pcs.test.amqp.Consumer.java
License:Open Source License
public static void main(String[] args) throws IOException, TimeoutException, ShutdownSignalException, ConsumerCancelledException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("pcss-hdop04"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println("listen for messages"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String msg = new String(delivery.getBody(), "UTF-8"); System.out.println("Msg received " + msg); }/*from ww w .java 2 s . c o m*/ }
From source file:com.pcs.test.amqp.Publisher.java
License:Open Source License
public static void main(String[] args) throws IOException, TimeoutException { System.out.println("starting"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("pcss-hdop04"); factory.setAutomaticRecoveryEnabled(true); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "first message , hello world"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println("message sent"); channel.close();//from ww w.j av a 2 s . c om connection.close(); }