1.添加依赖包
implementation 'com.rabbitmq:amqp-client:4.4.1'
2.连接mq设置
private void setUpConnectionFactory() {
factory.setHost("172.20.10.2");//服务器host
factory.setPort(5672);//注意端口
factory.setUsername("root");//用户名
factory.setPassword("root");//密码
}
3.接收服务器发来的消息
private Thread mqThread;
private Connection connection;
private ConnectionFactory factory
void getMqMessage(){
mqThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// 需要再次初始化数据的时候就关闭上一个连接
if(connection!= null){
connection.close();
}
// 创建新的连接
connection= factory.newConnection();
// 创建通道
Channel channel = connection.createChannel();
// 处理完一个消息,再接收下一个消息
channel.basicQos(1);
String queueName = System.currentTimeMillis();
// 声明交换机类型
channel.exchangeDeclare("amq.direct", "direct", true);
// 声明队列
AMQP.Queue.DeclareOk q = channel.queueDeclare(queueName, true, false, true, null);// 声明共享队列
// 根据路由键将队列绑定到交换机上
channel.queueBind(q.getQueue(), "amq.direct", "hk");
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
// 通过geiBody方法获取消息中的数据
String message = new String(body);
Log.i(TAG,message);
}
};
channel.basicConsume(q.getQueue(), true, consumer);
} catch (Exception e){
e.printStackTrace();
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
});
mqThread.start();// 开启线程获取RabbitMQ推送消息
}
4.RabbitMq服务器发送消息操作
5.控制台接收消息