安装RabbitMQ
- docker拉取镜像
docker pull rabbitmq:management
- 运行容器
docker run -d --hostname my-rabbit --name some-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:management
- 浏览器访问
默认超级用户 guest guest
入门实例
导入依赖
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
编写工具类(获取连接)
public class ConnectionUtils {
/**
* 获取MQ的连接
* @return
*/
public static Connection getConnection() throws IOException, TimeoutException {
//定义一个连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置服务地址
factory.setHost("192.168.188.172");
//AMQP 5672
factory.setPort(5672);
//vhost
factory.setVirtualHost("/vhost_xiaowen");
//用户名
factory.setUsername("root");
//密码
factory.setPassword("1234");
return factory.newConnection();
}
简单队列(一个生产者,一个消费者)
编写生产者
public class Producer {
private static final String QUEUE_NAME="my_first_queue";
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//从连接中获取一个通道
Channel channel = connection.createChannel();
//创建队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String message = "hello rabbitmq";
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println("发送一条消息:" + message);
//释放资源
channel.close();
connection.close();
}
}
编写接收者
public class Receiver {
private static final String QUEUE_NAME="my_first_queue";
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//从连接中获取通道
Channel channel = connection.createChannel();
//队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
DefaultConsumer 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");
System.out.println("接受一条消息" + message);
}
};
channel.basicConsume(QUEUE_NAME,true,consumer);
}
}
不足
耦合性高,生产者一一对应消费者,如果想多个消费者消费队列中的消息就不行了,队列名变更的话,要同时变更
Work queue工作队列(一对多)
编写生产者
public class Producer {
private static final String QUEUE_NAME="my_first_queue";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//从连接中获取一个通道
Channel channel = connection.createChannel();
//创建队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
for (int i = 0; i < 50; i++) {
String message = "hello rabbitmq"+ i;
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println("send:" + message);
Thread.sleep(i*20);
}
//释放资源
channel.close();
connection.close();
}
}
编写消费者
- 消费者一
public class Receiver1 {
private static final String QUEUE_NAME="my_first_queue";
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//从连接中获取通道
Channel channel = connection.createChannel();
//队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
DefaultConsumer 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");
System.out.println("Receiver [1]:" + message);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Receiver [1]: done");
}
}
};
channel.basicConsume(QUEUE_NAME,true,consumer);
}
}
- 消费者二
public class Receiver2 {
private static final String QUEUE_NAME="my_first_queue";
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//从连接中获取通道
Channel channel = connection.createChannel();
//队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
DefaultConsumer 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");
System.out.println("Receiver [2]:" + message);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Receiver [2]: done");
}
}
};
channel.basicConsume(QUEUE_NAME,true,consumer);
}
}
现象
消费者1并没有因为sleep时间比消费者2长而漏收或少收到消息
这种方式叫做轮询分发(round-robin)
公平分发fair dispatch
使用公平分发必须关闭自动应答-autoACK,并且要手动回执
编写生产者
public class Producer {
private static final String QUEUE_NAME="my_first_queue";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//从连接中获取一个通道
Channel channel = connection.createChannel();
//创建队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
/**
* 每个消费者发送确认消息之前,消息队列不发送下一个消息到消费者,一次只处理要给消息
* 限制发送个同一个消费者,不得超过一条消息
*/
int prefetchCount = 1;
channel.basicQos(prefetchCount);
for (int i = 0; i < 50; i++) {
String message = "hello rabbitmq"+ i;
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println("send:" + message);
Thread.sleep(i*10);
}
//释放资源
channel.close();
connection.close();
}
编写消费者
- 消费者一
public class Receiver1 {
private static final String QUEUE_NAME="my_first_queue";
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//从连接中获取通道
Channel channel = connection.createChannel();
//队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
channel.basicQos(1);//保证一次只分发一个
DefaultConsumer 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");
System.out.println("Receiver [1]:" + message);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Receiver [1]: done");
//手动回执
channel.basicAck(envelope.getDeliveryTag(),false);
}
}
};
boolean autoACK = false;//自动应答
channel.basicConsume(QUEUE_NAME,autoACK,consumer);
}
}
- 消费者二
public class Receiver2 {
private static final String QUEUE_NAME="my_first_queue";
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//从连接中获取通道
Channel channel = connection.createChannel();
//队列声明
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
channel.basicQos(1);//保证一次只分发一个
DefaultConsumer 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");
System.out.println("Receiver [2]:" + message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Receiver [2]: done");
//手动回执
channel.basicAck(envelope.getDeliveryTag(),false);
}
}
};
boolean autoACK = false;//自动应答
channel.basicConsume(QUEUE_NAME,autoACK,consumer);
}
}
现象
消费者二处理的消息比消费者二多,能者多劳
事务
try {
channel.txSelect();//开启事务
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println("send:"+message);
// int i = 1/0;
channel.txCommit();//提交
} catch (Exception e){
channel.txRollback();//回滚
System.out.println("发送失败");
}
confirm模式
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//获取通道
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String message = "confirm test";
channel.confirmSelect();
channel.basicPublish("",QUEUE_NAME,null, message.getBytes());
if (!channel.waitForConfirms()) {
System.out.println("send message failed");
} else {
System.out.println("发送消息:"+message);
}
channel.close();
connection.close();
}