最近工作中需要用到rabbitmq,踩到的坑记录一下。
1. windows安装rabbit
2. 启动rabbit
默认的用户为guest,该账号自能让我们本机登录,为了远程使用再创建一个。
1. 个人认为web页面创建更简单一点。
权限选择admin。
2. 之后点击管理员的名字,给他所有的权限都赋予一遍
都给他把权限附上。
3. 开始愉快的往队列发送消息
要点在web端打开的端口号是http://localhost:15672/,使用java远程连接端口号是5672。
public class MQSendtest {
private final static String QUEUE_NAME = "Queue1";
private final static String EXCHANGE_NAME = "OOK";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = getConn();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT,false,false,null);
// 接下来,我们创建一个channel,绝大部分API方法需要通过调用它来完成。
// 发送之前,我们必须声明消息要发往哪个队列,然后我们可以向队列发一条消息:
//channel.queueDeclare(QUEUE_NAME, false, false, false, null);
for(int i =0;i<10;i++){
String message = "Hello worlcdssd"+i;
channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
channel.close();
connection.close();
}
public static Connection getConn() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(5672); //默认端口号
factory.setVirtualHost("/");
factory.setUsername("admin");//默认用户名
factory.setPassword("admin");//默认密码
Connection connection = factory.newConnection();
return connection;
}
}
public class MQReceive1test {
private final static String QUEUE_NAME = "Queue1";
private final static String EXCHANGE_NAME = "OOK";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = MQSendtest.getConn();
final Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
// 绑定交换机,指定路由键为error
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);
// 保证一次只分发一条消息
//channel.basicQos(1);
DeliverCallback deliverCallback = new DeliverCallback() {
@Override
public void handle(String consumerTag, Delivery delivery) throws IOException {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" +
delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, new CancelCallback(){
@Override
public void handle(String consumerTag) throws IOException {
}
});
}
}
注意,使用DIRECT模式的交换器,当两个消费者同时订阅了一个队列时,一条消息只能被其中一个消费者消费。