消息队列目前流行的有三种
- RabbitMQ
- ActiveMQ
- Kafka
这三种都非常强大,RabbitMQ目前用的比较多,也比较流行,阿里也在用
ActiveMQ是阿帕奇出品,但是性能上和RMQ相比相对差一些
卡夫卡呢,使用场景不同,不多介绍,主要是用于日志收集方面,结合hadoop非常灵活
RabbitMQ官网:http://www.rabbitmq.com/
安装不多说了,可以下载Windows版本,或者linux版本 下载页面:http://www.rabbitmq.com/download.html
我在linux虚拟机上安装的,安装步骤简单,rpm直接安装就行,步骤就略了
成功后可以看到如下页面:

简答队列图

pom方面需要引入如下jar包
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
</dependencies>
定义一个类似连接池的类
public class Send {
private final static String QUEUE_NAME = "test_queue";
public static void main(String[] argv) throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtil.getConnection();
// 从连接中创建通道
Channel channel = connection.createChannel();
// 声明(创建)队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 消息内容
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
// 关闭通道和连接
channel.close();
connection.close();
}
}
创建消费者
public class Recv {
private final static String QUEUE_NAME = "test_queue";
public static void main(String[] argv) throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 定义队列的消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
// 监听队列
channel.basicConsume(QUEUE_NAME, true, consumer);
// 获取消息
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}
}
debug的时候可以进入rmq的管理页面查看对于的连接数,频道,以及消息队列:




消费者接受到的消息:

对应的官网英文文档如下:
http://www.rabbitmq.com/getstarted.html
网友评论