Java Code Examples for com.rabbitmq.client.QueueingConsumer#Delivery
The following examples show how to use
com.rabbitmq.client.QueueingConsumer#Delivery .
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: Message.java From storm-rabbitmq with MIT License | 6 votes |
private DeliveredMessage(QueueingConsumer.Delivery delivery) { super(delivery.getBody()); redelivery = delivery.getEnvelope().isRedeliver(); deliveryTag = delivery.getEnvelope().getDeliveryTag(); routingKey = delivery.getEnvelope().getRoutingKey(); exchange = delivery.getEnvelope().getExchange(); className = delivery.getProperties().getClassName(); clusterId = delivery.getProperties().getClusterId(); contentEncoding = delivery.getProperties().getContentEncoding(); contentType = delivery.getProperties().getContentType(); correlationId = delivery.getProperties().getCorrelationId(); deliveryMode = delivery.getProperties().getDeliveryMode(); expiration = delivery.getProperties().getExpiration(); headers = delivery.getProperties().getHeaders(); messageId = delivery.getProperties().getMessageId(); priority = delivery.getProperties().getPriority(); replyTo = delivery.getProperties().getReplyTo(); timestamp = delivery.getProperties().getTimestamp(); type = delivery.getProperties().getType(); userId = delivery.getProperties().getUserId(); }
Example 2
Source File: AMQPWorkflowConsumer2.java From reactive with Creative Commons Zero v1.0 Universal | 6 votes |
public void execute() throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("trade.eq.q", true, consumer); QueueingConsumer.Delivery msg = null; while (true) { try { msg = consumer.nextDelivery(); String message = new String(msg.getBody()); System.out.println("received: " + message); String[] parts = message.split(","); long shares = new Long(parts[2]).longValue(); Thread.sleep(1000); } catch (Exception e) { System.out.println("error with trade: " + e.getMessage()); System.out.println("sending to workflow"); channel.basicPublish("", "workflow.q", null, msg.getBody()); } } }
Example 3
Source File: RabbitConsumer.java From java-study with Apache License 2.0 | 6 votes |
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); // 打开连接和创建频道,与发送端一样 Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。 channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); // 创建队列消费者 QueueingConsumer consumer = new QueueingConsumer(channel); // 指定消费队列 channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { //消费者程序运行开着 如果生产者新增了数据会自动获取 Thread.sleep(500); // nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法) QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println("'[x] Received '" + message ); } }
Example 4
Source File: ClientReceive1.java From java-study with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws java.io.IOException,java.lang.InterruptedException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException{ ConnectionFactory factory=new ConnectionFactory(); // factory.setHost("localhost"); // factory.setVirtualHost("my_mq"); // factory.setUsername("zhxia"); // factory.setPassword("123456"); factory.setUri("amqp://guest:[email protected]:5672");//获取url Connection connection=factory.newConnection(); Channel channel=connection.createChannel(); channel.queueDeclare(queue_name, durable, false, false, null); System.out.println("Wait for message"); channel.basicQos(1); //消息分发处理 QueueingConsumer consumer=new QueueingConsumer(channel); channel.basicConsume(queue_name, autoAck, consumer); while(true){ Thread.sleep(500); QueueingConsumer.Delivery deliver=consumer.nextDelivery(); String message=new String(deliver.getBody()); System.out.println("Message received:"+message); channel.basicAck(deliver.getEnvelope().getDeliveryTag(), false); } }
Example 5
Source File: AMQPConsumer.java From reactive with Creative Commons Zero v1.0 Universal | 6 votes |
public void execute(String mode) throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("trade.request.q", true, consumer); if (mode.equalsIgnoreCase("stable")) {lower = 300; upper = 1200;} if (mode.equalsIgnoreCase("better")) {lower = 300; upper = 800;} if (mode.equalsIgnoreCase("worse")) {lower = 800; upper = 1900;} if (mode.equalsIgnoreCase("erratic")) {lower = 200; upper = 5000;} while (true) { QueueingConsumer.Delivery message = consumer.nextDelivery(); String msg = new String(message.getBody()); System.out.println("trade order received: " + msg); int response = lower + (int) (Math.random() * (upper-lower)); System.out.println("trade placed, duration = " + response); String newMsg = "response"; byte[] bmsg = newMsg.getBytes(); Thread.sleep(response); channel.basicPublish("", "trade.response.q", null, bmsg); } }
Example 6
Source File: AMQPContConsumer.java From reactive with Creative Commons Zero v1.0 Universal | 5 votes |
public static void main(String[] args) throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicQos(1); channel.basicConsume("trade.eq.q", false, consumer); while (true) { QueueingConsumer.Delivery msg = consumer.nextDelivery(); System.out.println("received: " + new String(msg.getBody())); Thread.sleep(2000); channel.basicAck(msg.getEnvelope().getDeliveryTag(), false); } }
Example 7
Source File: AMQPWorkflowConsumer.java From reactive with Creative Commons Zero v1.0 Universal | 5 votes |
public void execute() throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("trade.eq.q", true, consumer); while (true) { QueueingConsumer.Delivery msg = consumer.nextDelivery(); String message = new String(msg.getBody()); System.out.println("received: " + message); String[] parts = message.split(","); long shares = new Long(parts[2]).longValue(); Thread.sleep(1000); } }
Example 8
Source File: AMQPConfig.java From reactive with Creative Commons Zero v1.0 Universal | 5 votes |
public void execute() throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("config.q", true, consumer); //cleanup any left over messages before continuing... while (true) { if (consumer.nextDelivery(1000) == null) break; System.out.print("."); } System.out.println(""); System.out.println("place_trade_low: - (-)"); System.out.println("place_trade_current: 2000 (1000) <=="); System.out.println("place_trade_high: - (-)"); System.out.println(""); while (true) { QueueingConsumer.Delivery message = consumer.nextDelivery(); String msg = new String(message.getBody()); String[] values = msg.split(","); long low = new Long(values[0]); long cur = new Long(values[1]); long high = new Long(values[2]); //message in low,med,high format (duration) System.out.println("place_trade_low: " + low*2 + " (" + low + ")"); System.out.println("place_trade_current: " + cur*2 + " (" + cur + ") <=="); System.out.println("place_trade_high: " + high*2 + " (" + high + ")"); System.out.println(""); } }
Example 9
Source File: Dispatcher.java From reactive with Creative Commons Zero v1.0 Universal | 5 votes |
public void dispatchMessages() throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicQos(1); channel.basicConsume("trade.eq.q", false, consumer); java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Display Allocation Map? (y/n): "); display = input.next().equalsIgnoreCase("y"); input.close(); //start with 5 threads... for (long i=1;i<6;i++) { TradeProcessor processor = new TradeProcessor(this, i); threadpool.put(i, processor); processingCountMap.put(i, 0L); new Thread(()->processor.start()).start(); } displayAllocationMap(); while (true) { QueueingConsumer.Delivery msg = consumer.nextDelivery(); channel.basicAck(msg.getEnvelope().getDeliveryTag(), false); String trade = new String(msg.getBody()); String context = getContext(trade); Long threadId = 0L; if (allocationMap.containsKey(context)) { threadId = allocationMap.get(context); } else { threadId = getNextAvailableThread(); allocationMap.put(context, threadId); } processingCountMap.put(threadId, processingCountMap.get(threadId)+1); if (display) System.out.println("Dispatcher: Received " + trade); displayAllocationMap(); threadpool.get(threadId).addMessage(new String(msg.getBody())); } }
Example 10
Source File: TradeReader.java From ThriftBook with Apache License 2.0 | 5 votes |
public static void main(String[] argv) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.TimeoutException, TException, TTransportException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); System.out.println("Waiting for trade reports..."); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); byte[] data = delivery.getBody(); TMemoryBuffer trans = new TMemoryBuffer(data.length); trans.write(data, 0, data.length); TCompactProtocol proto = new TCompactProtocol(trans); TradeReport tr = new TradeReport(); tr.read(proto); System.out.println("[" + tr.seq_num + "] " + tr.symbol + " @ " + tr.price + " x " + tr.size); } }
Example 11
Source File: Consumer.java From rabbitmq-tutorial with MIT License | 5 votes |
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://guest:guest@localhost"); factory.setConnectionTimeout(300000); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("my-queue", true, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("my-queue", false, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); if (delivery != null) { try { String message = new String(delivery.getBody(), StandardCharsets.UTF_8); System.out.println("Message consumed: " + message); // Interact with IO channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (Exception e) { channel.basicReject(delivery.getEnvelope().getDeliveryTag(), true); } } } }
Example 12
Source File: Recv.java From java-study with Apache License 2.0 | 5 votes |
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); // factory.setHost("localhost"); // factory.setHost("127.0.0.1"); factory.setUri("amqp://guest:[email protected]:5672");//获取url // 打开连接和创建频道,与发送端一样 Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。 channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); // 创建队列消费者 QueueingConsumer consumer = new QueueingConsumer(channel); // 指定消费队列 channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { //消费者程序运行开着 如果生产者新增了数据会自动获取 Thread.sleep(500); List aa=new ArrayList(); // nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法) QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); aa.add(message); System.out.println("你好吗!"+" [x] Received '" + message + "'"+aa); } }
Example 13
Source File: Worker.java From java-study with Apache License 2.0 | 5 votes |
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); //factory.setHost("localhost"); factory.setUri("amqp://guest:[email protected]:5672"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);//queue的持久化需要在声明时指定durable=True System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); //保证在接收端一个消息没有处理完时不会接收另一个消息 channel.basicQos(1); // channel.basicQos(0, 1, false); //这样RabbitMQ就会使得每个Consumer在同一个时间点最多处理一个Message。换句话说,在接收到该Consumer的ack前,他它不会将新的Message分发给它。 QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(TASK_QUEUE_NAME, false, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); doWork(message); System.out.println(" [x] Done"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
Example 14
Source File: CacheInvalidationSubscriber.java From carbon-commons with Apache License 2.0 | 5 votes |
@Override public void run() { while(consumer != null) { try { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); onMessage(delivery.getBody()); } catch (Exception e) { log.error("Global cache invalidation: error message recieve.", e); } } }
Example 15
Source File: RabbitIntegrationTest.java From brooklyn-library with Apache License 2.0 | 5 votes |
/** * Test that an AMQP client can connect to and use the broker. */ @Test(groups = {"Integration", "WIP"}) public void testClientConnection() throws Exception { rabbit = app.createAndManageChild(EntitySpec.create(RabbitBroker.class)); rabbit.start(ImmutableList.of(testLocation)); EntityAsserts.assertAttributeEqualsEventually(rabbit, Startable.SERVICE_UP, true); byte[] content = "MessageBody".getBytes(Charsets.UTF_8); String queue = "queueName"; Channel producer = null; Channel consumer = null; try { producer = getAmqpChannel(rabbit); consumer = getAmqpChannel(rabbit); producer.queueDeclare(queue, true, false, false, ImmutableMap.<String,Object>of()); producer.queueBind(queue, AmqpExchange.DIRECT, queue); producer.basicPublish(AmqpExchange.DIRECT, queue, null, content); QueueingConsumer queueConsumer = new QueueingConsumer(consumer); consumer.basicConsume(queue, true, queueConsumer); QueueingConsumer.Delivery delivery = queueConsumer.nextDelivery(60 * 1000l); // one minute timeout assertEquals(delivery.getBody(), content); } finally { closeSafely(producer, 10*1000); closeSafely(consumer, 10*1000); } }
Example 16
Source File: RabbitEc2LiveTest.java From brooklyn-library with Apache License 2.0 | 5 votes |
@Override protected void doTest(Location loc) throws Exception { RabbitBroker rabbit = app.createAndManageChild(EntitySpec.create(RabbitBroker.class)); rabbit.start(ImmutableList.of(loc)); EntityAsserts.assertAttributeEqualsEventually(rabbit, RabbitBroker.SERVICE_UP, true); byte[] content = "MessageBody".getBytes(Charsets.UTF_8); String queue = "queueName"; Channel producer = null; Channel consumer = null; try { producer = getAmqpChannel(rabbit); consumer = getAmqpChannel(rabbit); producer.queueDeclare(queue, true, false, false, Maps.<String,Object>newHashMap()); producer.queueBind(queue, AmqpExchange.DIRECT, queue); producer.basicPublish(AmqpExchange.DIRECT, queue, null, content); QueueingConsumer queueConsumer = new QueueingConsumer(consumer); consumer.basicConsume(queue, true, queueConsumer); QueueingConsumer.Delivery delivery = queueConsumer.nextDelivery(); assertEquals(delivery.getBody(), content); } finally { if (producer != null) producer.close(); if (consumer != null) consumer.close(); } }
Example 17
Source File: SampleMessageLitener.java From AsuraFramework with Apache License 2.0 | 4 votes |
@Override public void processMessage(QueueingConsumer.Delivery delivery) { System.out.println("[" + delivery.getEnvelope().getRoutingKey() + "][receive:" + new String(delivery.getBody()) + "]"); }
Example 18
Source File: Worker.java From neo4j-mazerunner with Apache License 2.0 | 4 votes |
public void doMain(String[] args) throws Exception { CmdLineParser parser = new CmdLineParser(this); // if you have a wider console, you could increase the value; // here 80 is also the default parser.setUsageWidth(80); try { // parse the arguments. parser.parseArgument(args); if(sparkMaster == "" || hadoopHdfs == "") throw new CmdLineException(parser, "Options required: --hadoop.hdfs <url>, --spark.master <url>"); ConfigurationLoader.getInstance().setHadoopHdfsUri(hadoopHdfs); ConfigurationLoader.getInstance().setSparkHost(sparkMaster); ConfigurationLoader.getInstance().setAppName(sparkAppName); ConfigurationLoader.getInstance().setExecutorMemory(sparkExecutorMemory); ConfigurationLoader.getInstance().setDriverHost(driverHost); ConfigurationLoader.getInstance().setRabbitmqNodename(rabbitMqHost); } catch( CmdLineException e ) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("java -cp $CLASSPATH [<spark-config-options>] <main-class> [<mazerunner-args>]"); // print the list of available options parser.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java -cp $CLASSPATH org.mazerunner.core.messaging.Worker"+parser.printExample(ALL)); return; } ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); channel.basicQos(20); // Initialize spark context GraphProcessor.initializeSparkContext(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(TASK_QUEUE_NAME, false, consumer); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); // Deserialize message Gson gson = new Gson(); ProcessorMessage processorMessage = gson.fromJson(message, ProcessorMessage.class); // Run PageRank GraphProcessor.processEdgeList(processorMessage); System.out.println(" [x] Done '" + message + "'"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
Example 19
Source File: MQRecver.java From jlitespider with Apache License 2.0 | 4 votes |
public MQItem recv() throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); MQItem item = gson.fromJson(new String(delivery.getBody()), MQItem.class); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); return item; }
Example 20
Source File: Message.java From storm-rabbitmq with MIT License | 4 votes |
public static Message forDelivery(QueueingConsumer.Delivery delivery) { return (delivery != null) ? new DeliveredMessage(delivery) : NONE; }