List of usage examples for com.rabbitmq.client Channel basicPublish
void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;
From source file:reactor.rabbitmq.ReactorRabbitMqTests.java
License:Open Source License
@Test public void receiverConsumeAutoAck() throws Exception { Channel channel = connection.createChannel(); int nbMessages = 10; receiver = ReactorRabbitMq.createReceiver(); for (int $ : IntStream.range(0, 10).toArray()) { Flux<Delivery> flux = receiver.consumeAutoAck(queue); for (int $$ : IntStream.range(0, nbMessages).toArray()) { channel.basicPublish("", queue, null, "Hello".getBytes()); }// w w w . j av a2 s. co m CountDownLatch latch = new CountDownLatch(nbMessages * 2); AtomicInteger counter = new AtomicInteger(); Disposable subscription = flux.subscribe(msg -> { counter.incrementAndGet(); latch.countDown(); }); for (int $$ : IntStream.range(0, nbMessages).toArray()) { channel.basicPublish("", queue, null, "Hello".getBytes()); } assertTrue(latch.await(1, TimeUnit.SECONDS)); subscription.dispose(); assertEquals(nbMessages * 2, counter.get()); } assertNull(connection.createChannel().basicGet(queue, true)); }
From source file:reactor.rabbitmq.ReactorRabbitMqTests.java
License:Open Source License
@Test public void receiverConsumeManuelAck() throws Exception { Channel channel = connection.createChannel(); int nbMessages = 10; receiver = ReactorRabbitMq.createReceiver(); for (int $ : IntStream.range(0, 10).toArray()) { Flux<AcknowledgableDelivery> flux = receiver.consumeManuelAck(queue); for (int $$ : IntStream.range(0, nbMessages).toArray()) { channel.basicPublish("", queue, null, "Hello".getBytes()); }// w w w . j av a2 s. c om CountDownLatch latch = new CountDownLatch(nbMessages * 2); AtomicInteger counter = new AtomicInteger(); Disposable subscription = flux.bufferTimeout(5, Duration.ofSeconds(1)).subscribe(messages -> { counter.addAndGet(messages.size()); messages.forEach(msg -> { msg.ack(); latch.countDown(); }); }); for (int $$ : IntStream.range(0, nbMessages).toArray()) { channel.basicPublish("", queue, null, "Hello".getBytes()); } assertTrue(latch.await(1, TimeUnit.SECONDS)); subscription.dispose(); assertEquals(nbMessages * 2, counter.get()); } assertNull(connection.createChannel().basicGet(queue, true)); }
From source file:reactor.rabbitmq.ReactorRabbitMqTests.java
License:Open Source License
@Test public void receiverConsumeManuelAckOverflowMessagesRequeued() throws Exception { // Downstream would request only one message and the hook before emission // would nack/requeue messages. // Messages are then redelivered, so there a nack can fail because // the channel is closed (the subscription is cancelled once the 20 // published messages have been acked (first one) and at least 19 have // been nacked. This can lead to some stack trace in the console, but // it's normal behavior. // This can be an example of trying no to loose messages and requeue // messages when the downstream consumers are overloaded Channel channel = connection.createChannel(); int nbMessages = 10; receiver = ReactorRabbitMq.createReceiver(); CountDownLatch ackedNackedLatch = new CountDownLatch(2 * nbMessages - 1); Flux<AcknowledgableDelivery> flux = receiver.consumeManuelAck(queue, new ReceiverOptions() .overflowStrategy(FluxSink.OverflowStrategy.DROP).hookBeforeEmit((emitter, message) -> { if (emitter.requestedFromDownstream() == 0) { message.nack(true);//from w ww. ja va 2 s .c o m ackedNackedLatch.countDown(); return false; } else { return true; } }).qos(1)); for (int $$ : IntStream.range(0, nbMessages).toArray()) { channel.basicPublish("", queue, null, "Hello".getBytes()); } CountDownLatch latch = new CountDownLatch(1); AtomicInteger counter = new AtomicInteger(); AtomicReference<Subscription> subscriptionReference = new AtomicReference<>(); flux.subscribe(new BaseSubscriber<AcknowledgableDelivery>() { @Override protected void hookOnSubscribe(Subscription subscription) { subscription.request(1); subscriptionReference.set(subscription); } @Override protected void hookOnNext(AcknowledgableDelivery message) { try { Thread.sleep(100L); } catch (InterruptedException e) { e.printStackTrace(); } counter.addAndGet(1); message.ack(); latch.countDown(); subscriptionReference.get().request(0); } }); for (int $$ : IntStream.range(0, nbMessages).toArray()) { channel.basicPublish("", queue, null, "Hello".getBytes()); } assertTrue(latch.await(1, TimeUnit.SECONDS)); assertTrue(ackedNackedLatch.await(1, TimeUnit.SECONDS)); subscriptionReference.get().cancel(); assertEquals(1, counter.get()); assertTrue(connection.createChannel().queueDeclarePassive(queue).getMessageCount() > 0); }
From source file:reactor.rabbitmq.ReactorRabbitMqTests.java
License:Open Source License
@Test public void receiverConsumeManuelAckOverflowMessagesDropped() throws Exception { // downstream would request only one message and the hook before emission // would ack other messages. // This can be an example of controlling back pressure by dropping // messages (because they're non-essential) with RabbitMQ QoS+ack and // reactor feedback from downstream. Channel channel = connection.createChannel(); int nbMessages = 10; receiver = ReactorRabbitMq.createReceiver(); CountDownLatch ackedDroppedLatch = new CountDownLatch(2 * nbMessages - 1); Flux<AcknowledgableDelivery> flux = receiver.consumeManuelAck(queue, new ReceiverOptions() .overflowStrategy(FluxSink.OverflowStrategy.DROP).hookBeforeEmit((emitter, message) -> { if (emitter.requestedFromDownstream() == 0) { message.ack();/* w w w .j a v a 2 s.com*/ ackedDroppedLatch.countDown(); } // we can emit, the message will be dropped by the overflow strategy return true; }).qos(1)); for (int $$ : IntStream.range(0, nbMessages).toArray()) { channel.basicPublish("", queue, null, "Hello".getBytes()); } CountDownLatch latch = new CountDownLatch(1); AtomicInteger counter = new AtomicInteger(); AtomicReference<Subscription> subscriptionReference = new AtomicReference<>(); flux.subscribe(new BaseSubscriber<AcknowledgableDelivery>() { @Override protected void hookOnSubscribe(Subscription subscription) { subscription.request(1); subscriptionReference.set(subscription); } @Override protected void hookOnNext(AcknowledgableDelivery message) { try { Thread.sleep(100L); } catch (InterruptedException e) { e.printStackTrace(); } counter.addAndGet(1); message.ack(); latch.countDown(); subscriptionReference.get().request(0); } }); for (int $$ : IntStream.range(0, nbMessages).toArray()) { channel.basicPublish("", queue, null, "Hello".getBytes()); } assertTrue(ackedDroppedLatch.await(1, TimeUnit.SECONDS)); assertTrue(latch.await(1, TimeUnit.SECONDS)); subscriptionReference.get().cancel(); assertEquals(1, counter.get()); assertNull(connection.createChannel().basicGet(queue, true)); }
From source file:ru.kinomir.queue.QueueSender.java
public synchronized void sendToQueue(Object data, String queueName, String queueHost, String userName, String password, String port, String virtualHost) { Channel channel = null; Connection connection = null; try {// w ww.j a v a 2 s. c om logger.info("Send message to queue '" + queueName + "'"); ConnectionFactory factory = new ConnectionFactory(); if (!StringTools.isEmpty(userName)) { factory.setUsername(userName); } if (!StringTools.isEmpty(password)) { factory.setPassword(password); } if (!StringTools.isEmpty(port)) { try { factory.setPort(Integer.parseInt(port)); } catch (NumberFormatException ignore) { } } if (!StringTools.isEmpty(virtualHost)) { factory.setVirtualHost(virtualHost); } factory.setHost(queueHost); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(queueName, true, false, false, null); String message = convertToString(data); logger.info("Message text: " + message); channel.basicPublish("", queueName, MessageProperties.MINIMAL_PERSISTENT_BASIC, message.getBytes()); logger.info("Message was sent"); } catch (Exception ex) { logger.error("Uneble send message: " + convertToString(data)); logger.debug(ex.getMessage(), ex); } finally { try { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } catch (Exception ignore) { } } }
From source file:samples.userguide.RabbitMQAMQPClient.java
License:Apache License
public static void main(String[] args) { String queueName = System.getProperty("queueName"); String mode = System.getProperty("mode"); String routingKey = System.getProperty("routingKey"); String exchangeName = System.getProperty("exchangeName"); String quote = System.getProperty("payLoad"); if (quote == null) { quote = "IBM"; }/*from w w w . ja v a2 s. com*/ String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + " <m:order>\n" + " <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + " <m:quantity>" + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + " <m:symbol>" + quote + "</m:symbol>\n" + " </m:order>\n" + "</m:placeOrder>"; ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = null; Channel channel = null; try { connection = factory.newConnection(); channel = connection.createChannel(); if (mode == null) { mode = "producer"; } if ("producer".equals(mode)) { if (queueName != null) { channel.basicPublish("", queueName, null, msg.getBytes()); } else { if (routingKey != null) { if (exchangeName == null) { exchangeName = "topic-exchange"; } channel.basicPublish(exchangeName, routingKey, null, msg.getBytes()); } else { if (exchangeName == null) { exchangeName = "subscriber-exchange"; } channel.basicPublish(exchangeName, "", null, msg.getBytes()); } } } else { if (queueName == null) { queueName = "ConsumerProxy"; } QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println("[x] received '" + message + "'"); } channel.close(); connection.close(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException e) { System.err.println("Error occurred while closing the channel:" + e.getMessage()); } } if (connection != null && connection.isOpen()) { try { connection.close(); } catch (IOException e) { System.err.println("Error occurred while closing the connection:" + e.getMessage()); } } } }
From source file:sd_aula06.Send.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("reindeer.rmq.cloudamqp.com"); factory.setUsername("jmodzuaw"); factory.setPassword("Kwuy7kd81ED1fIj9gxEti1J4FTPBj2Jz"); factory.setVirtualHost("jmodzuaw"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "RafaelReis: VSF!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); channel.close();/*from www . ja v a 2s .co m*/ connection.close(); }
From source file:server.Worker.java
License:Open Source License
/** * @param args/* w w w . j a v a2 s . co m*/ * @throws IOException * @throws TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection requestConnection = factory.newConnection(); Channel requestChannel = requestConnection.createChannel(); requestChannel.queueDeclare(REQUEST_QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Connection responseConnection = factory.newConnection(); final Channel responseChannel = responseConnection.createChannel(); responseChannel.queueDeclare(RESPONSE_QUEUE_NAME, false, false, false, null); Consumer consumer = new DefaultConsumer(requestChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { PriorityRequest request = (PriorityRequest) SerializationUtils.deserialize(body); System.out.println(" [x] Received"); System.out.println(request.request.toString()); System.out.println("*************************************"); System.out.println(request.request.getMethod()); HttpResponse response = PluginManager.getInstance().process(request.request, request.rootDir); if (response == null) { response = HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } try { System.out.println(request.id); } catch (Exception e) { e.printStackTrace(); } response.id = request.id; byte[] data = SerializationUtils.serialize(response); responseChannel.basicPublish("", RESPONSE_QUEUE_NAME, null, data); } }; requestChannel.basicConsume(REQUEST_QUEUE_NAME, true, consumer); }
From source file:server.WorkerServer.java
License:Open Source License
private void doWork(HttpRequest request) throws Exception { // Parse the request try {/*w w w .ja va 2 s .c o m*/ String[] uri = request.getUri().split("/"); String requestTypeString = request.getMethod(); String pluginString = uri[1]; String servletString = uri[2]; HashMap<String, IPlugin> plugins = server.getPlugins(); IPlugin currPlugin = plugins.get(pluginString); if (currPlugin == null) { throw new ProtocolException(Protocol.NOT_FOUND_CODE, "This plugin doesn't exist"); } IServlet servlet = currPlugin.getServlet(requestTypeString + ":/" + servletString); if (servlet == null) { System.out.println("servlet is null"); throw new ProtocolException(Protocol.NOT_FOUND_CODE, "This servlet doesn't exist"); } System.out.println("requestTypeString: " + requestTypeString); HttpResponse response = servlet.processRequest(request, null); // publish response to response queue Connection connection2 = factory.newConnection(); Channel channel2 = connection2.createChannel(); boolean durable = true; //System.out.println("response: " + response.getBytes(request.getKey())); channel2.queueDeclare(Protocol.RESPONSE_QUEUE, durable, false, false, null); channel2.basicPublish("", Protocol.RESPONSE_QUEUE, MessageProperties.PERSISTENT_TEXT_PLAIN, response.getBytes(request.getKey())); } catch (ProtocolException e) { e.printStackTrace(); } }
From source file:sonata.kernel.vimadaptor.messaging.RabbitMqProducer.java
License:Open Source License
@Override public boolean sendMessage(ServicePlatformMessage message) { boolean out = true; // TODO maps the specific Adaptor message to the proper SP topic try {/*from w w w . ja va 2 s. c o m*/ Channel channel = connection.createChannel(); String exchangeName = brokerConfig.getProperty("exchange"); channel.exchangeDeclare(exchangeName, "topic"); BasicProperties properties = new BasicProperties().builder().appId(AdaptorCore.APP_ID) .contentType(message.getContentType()).replyTo(message.getReplyTo()) .correlationId(message.getSid()).build(); channel.basicPublish(exchangeName, message.getTopic(), properties, message.getBody().getBytes("UTF-8")); // Logger.info("Sending message: " + message + "\n\r - Properties:" + properties); } catch (Exception e) { Logger.error(e.getMessage(), e); out = false; } return out; }