rabbitmq官网:https://www.rabbitmq.com/
rabbitmq是erlang开发的,需要安装erlang环境
Erlang是一种功能编程语言,也具有运行时环境。
Erlang官网:https://www.erlang.org/
获取连接
java
public class RabbitMQConnection {
public static Connection getConnection() throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
// 设置连接虚拟机
connectionFactory.setVirtualHost("/meiteVirtualHosts");
// 设置账号密码
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
// 设置ip和端口
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
return connectionFactory.newConnection();
}
}
生产者
java
public class Producer {
public static final String QUEUE_NAME = "queue-name";
public static void main(String[] args) throws IOException, TimeoutException {
// 创建连接
Connection connection = RabbitMQConnection.getConnection();
// 创建通道
Channel channel = connection.createChannel();
String msg = "消息-" + new Date();
// 发布消息到队列
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
// 关闭通道和连接
channel.close();
connection.close();
}
}
消费者
java
public class Comsumer {
public static final String QUEUE_NAME = "queue-name";
public static void main(String[] args) throws IOException, TimeoutException {
// 创建连接
Connection connection = RabbitMQConnection.getConnection();
// 创建通道
Channel channel = connection.createChannel();
// 消费消息
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者:" + new String(body, StandardCharsets.UTF_8));
}
};
// 监听队列 autoAck:true自动签收,false手动签收
channel.basicConsume(QUEUE_NAME,true,defaultConsumer);
// 长连接不必关闭通道
//channel.close();
//connection.close();
}
}