- 添加依赖
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
- 创建帮助类
public class ConnectUtils {
public static Connection getConnection() throws IOException, TimeoutException {
//定义连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.44.142");
factory.setPort(5672);
factory.setVirtualHost("host1");
factory.setUsername("yorick");
factory.setPassword("199748");
Connection connection = null;
// 通过工厂获取连接
connection = factory.newConnection();
return connection;
}
}
- 发送消息(生产者)
public class SendMsg {
@Test
public void testSendMsg() throws IOException, TimeoutException {
Connection connection = ConnectUtils.getConnection();
Channel channel = connection.createChannel();
String msg = "Hello World";
//参数说明:
//参数1:交换机名称
//参数2:队列名称
//参数3:属性
//参数4:内容
//简单模式
channel.basicPublish("","queue1",null,msg.getBytes());
//工作模式
//channel.basicPublish("","queue2",null,msg.getBytes());
//订阅模式
//channel.basicPublish("ex1","",null,msg.getBytes());
//路由模式
//channel.basicPublish("ex2","k1",null,msg.getBytes());
//关闭通道和连接
channel.close();
connection.close();
}
}
- 接收消息(消费者)
public class ReceiveMsg {
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectUtils.getConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body);
System.out.println("consumer receive msg: " + msg);
}
};
//简单模式,工作模式,订阅模式,路由模式
channel.basicConsume("queue1", true, consumer);
}
}