1、创建RabbitMq连接
-
在pom.xml添加rabbit依赖
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.6.0</version> </dependency>
-
生产者
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class P {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
/*连接可以抽象为socket连接,为我们维护协议版本信息和协议证书等。这里我们连接
上了本机的消息服务器实体(localhost)。如果我们想连接其它主机上的RabbitMQ服务,只需要修改一下主机名或是IP就可以了*/
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.0.154");
factory.setPort(5672);
factory.setUsername("test");
factory.setPassword("test");
factory.setVirtualHost("/test");
Connection connection = factory.newConnection();
/*接下创建channel(信道),这是绝大多数API都能用到的。为了发送消息,你必须要声明一个消息消息队列,然后向该队列里推送消息*/
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
for(int i=1;i<100;i++) {
String m = message + String.valueOf(i);
channel.basicPublish("", QUEUE_NAME, null, m.getBytes("UTF-8"));
}
System.out.println("P [x] Sent '" + message + "'");
/*声明一个幂等的队列(只有在该队列不存在时,才会被创建)。消息的上下文是一个
字节数组,你可以指定它的编码。*/
channel.close();
connection.close();
}
}
- 消费者
import com.rabbitmq.client.*;
import java.io.IOException;
public class C {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
/*这里怎么打开连接和信道,以及声明用于接收消息的队列,这些步骤与发送端基本上是一样的*/
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.0.154");
factory.setPort(5672);
factory.setUsername("test");
factory.setPassword("test");
factory.setVirtualHost("/test");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
/*确保这里的队列是存在的*/
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("C [*] Waiting for messages. To exit press CTRL+C");
/*这里用到了额外的类QueueingConsumer来缓存服务器将要推过来的消息。我们通知服务器向接收端推送消息,然后服务器将会向客户端异步推送消息,这里提供了一个可以回调的对象来缓存消息,直到我们做好准备来使用 它,这个类就是QueueingConsumer*/
Consumer 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("C [x] Received '" + message + "'");
}
};
boolean autoAck = true;autoAck 是否自动确认消息,true自动确认,false 不自动要手动调用,建立设置为false
channel.basicConsume(QUEUE_NAME, autoAck, consumer);
}
}
- RabbitMq后台管理操作