当然首先第一步就是连接上 确保自己端口开放 (5672(消息端口)和 15672(web界面端口))
我这个是虚拟机中安装好的
导入依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.4.3</version>
</dependency>
创建连接工具类
package com.Utils;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ConnectionUtils {
public static Connection getConnection() throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.127.132");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
return factory.newConnection();
}
}
最普通的模式
先试着发送消息
package com.han;
import com.Utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
public class publish {
public static void main(String[] args) throws Exception {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
/**
* 声明一个队列。
* 参数一:队列名称
* 参数二:是否持久化
* 参数三:是否排外 如果排外则这个队列只允许有一个消费者
* 参数四:是否自动删除队列,如果为true表示没有消息也没有消费者连接自动删除队列
* 参数五:队列的附加属性
* 注意:
* 1.声明队列时,如果已经存在则放弃声明,如果不存在则会声明一个新队列;
* 2.队列名可以任意取值,但需要与消息接收者一致。
* 3.下面的代码可有可无,一定在发送消息前确认队列名称已经存在RabbitMQ中,否则消息会发送失败。
*/
channel.queueDeclare("queue7" ,false,false,false,null);
String message = "卧槽了";
channel.basicPublish("" ,"queue7" ,null ,message.getBytes());
System.out.println("消息发送成功");
channel.close();
connection.close();
}
}
然后接收消息
package com.han;
import com.Utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.*;
import java.io.IOException;
public class ReceiveMsg {
public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtils.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 {
//body就是从队列中获取的数据
String msg = new String(body);
System.out.println("接收到数据:"+msg);
}
};
channel.basicConsume("queue7",true,consumer);
}
}