Java使用RabbitMQ之公平分发
Posted 星瑞的随笔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java使用RabbitMQ之公平分发相关的知识,希望对你有一定的参考价值。
发送消息:
1 package org.study.workfair; 2 3 import com.rabbitmq.client.Channel; 4 import com.rabbitmq.client.Connection; 5 import org.junit.Test; 6 import org.study.utils.ConnectionUtils; 7 8 import java.io.IOException; 9 import java.util.concurrent.TimeoutException; 10 11 public class Sender { 12 public static final String QUEUE_NAME = "test_simple_queue"; 13 14 @Test 15 public void send() throws IOException, TimeoutException, InterruptedException { 16 // 获取连接 17 Connection conn = ConnectionUtils.getConnection(); 18 // 获取通道 19 Channel channel = conn.createChannel(); 20 //创建队列 21 channel.queueDeclare(QUEUE_NAME, false, false, false, null); 22 //每个消费者发送确认消息前,只发送一条消息 23 channel.basicQos(1); 24 String msg = "hello rabbitmq!"; 25 26 for (int i = 0; i < 50; i++) { 27 String tempStr = i + " " + msg; 28 //发送消息 29 channel.basicPublish("", QUEUE_NAME, null, tempStr.getBytes()); 30 System.out.println("[send] msg " + i + ": " + msg); 31 Thread.sleep(100); 32 } 33 34 channel.close(); 35 conn.close(); 36 } 37 }
接受消息:
1 package org.study.workfair; 2 3 import com.rabbitmq.client.*; 4 import org.junit.Test; 5 import org.study.utils.ConnectionUtils; 6 7 import java.io.IOException; 8 import java.util.concurrent.TimeoutException; 9 10 public class Recv { 11 public static final String QUEUE_NAME = "test_simple_queue"; 12 13 @Test 14 public void recv() throws IOException, TimeoutException, InterruptedException { 15 Connection conn = ConnectionUtils.getConnection(); 16 Channel channel = conn.createChannel(); 17 channel.queueDeclare(QUEUE_NAME, false, false, false, null); 18 channel.basicQos(1); 19 20 //定义消费者 21 DefaultConsumer consumer = new DefaultConsumer(channel) { 22 //重写获取到达消息 23 @Override 24 public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { 25 // super.handleDelivery(consumerTag, envelope, properties, body); 26 String msg = new String(body, "utf-8"); 27 System.out.println("[1] recv: " + msg); 28 29 try { 30 Thread.sleep(1000); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 }finally { 34 System.out.println("[1] done!"); 35 channel.basicAck(envelope.getDeliveryTag(),false); 36 } 37 } 38 }; 39 40 while (true) { 41 //监听队列 42 channel.basicConsume(QUEUE_NAME, false, consumer); 43 Thread.sleep(100); 44 } 45 46 47 } 48 }
以上是关于Java使用RabbitMQ之公平分发的主要内容,如果未能解决你的问题,请参考以下文章
RabbitMQ简单应用の公平分发(fair dipatch)
RabbitMQ学习第二记:工作队列的两种分发方式,轮询分发(Round-robin)和 公平分发(Fair dispatch)