1 : 需要的jar
下载地址:http://repo1.maven.org/maven2/com/rabbitmq/amqp-client/3.0.4/
maven配置:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.0.4</version>
</dependency>
注意:夹包的版本不同,有的类找不到,
列如:import com.rabbitmq.client.QueueingConsumer;-----在5.0.0版本中就没有,在3.0.4版本中有,其他版本需要自己测试
2:创建一个java工程,直接引入下面代码测试
=========================测试类开始===========================
package rabbitmq;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
public class TestMq {
public final static String QUEUE_NAME="rabbitMQ_test";
/**
* 建立连接,创建消息列队,并且向消息列队中发送一条消息
*/
@Test
public void linkSend(){
try {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置RabbitMQ相关信息
factory.setHost("192.168.146.134");
factory.setUsername("admin");
factory.setPassword("123");
factory.setPort(5672);
//创建一个新的连接
Connection connection = factory.newConnection();
//创建一个通道
Channel channel = connection.createChannel();
// 声明一个队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//发送消息到队列中
String message = "Hello RabbitMQ";
channel.basicPublish("",QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println("Producer Send +‘" + message + "‘");
//关闭通道和连接
channel.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 建立连接,创建消息列队,并且接收消息列队中的一条消息
*/
@Test
public void testReceive(){
try {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置RabbitMQ相关信息
factory.setHost("192.168.146.134");
factory.setUsername("admin");
factory.setPassword("123");
factory.setPort(5672);
//创建一个新的连接
Connection connection = factory.newConnection();
//创建一个通道
Channel channel = connection.createChannel();
//声明要连接的队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("等待消息产生:");
//创建消费者对象,用于读取消息
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
//获取消息列队中的消息,打印在控制台
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println("收到消息==============" + message);
//关闭通道和连接
channel.close();
connection.close();
} catch (ShutdownSignalException | ConsumerCancelledException
| IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
=========================测试类结束===========================
原文地址:https://www.cnblogs.com/xueershewang/p/9120956.html