一、流程
1.建立连接工厂ConnectionFactory
2.通过连接工厂ConnectionFactory建立连接Connection,相当于建立TCP连接
3.连接成功后建立信道Channel
4.发送消息与接受消息
5.关闭连接
二、环境
安装Erlang
安装rabbitMq
将amqp-client-5.7.3.jar导入项目
需注意Erlang与rabbitmq之间的版本匹配
三、连接工厂
public class RabbitMqConnectionUtil {
public static Connection getConnection() throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("localhost");
connectionFactory.setPort(5672);
return connectionFactory.newConnection();
}
}
四、生产者
public class Producer {
private static final String QUEUE_NAME = "TEST_QUEUE";
public static void main(String[] args) throws IOException, TimeoutException {
Scanner in = new Scanner(System.in);
Connection connection = RabbitMqConnectionUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String msg = "I'm a rabbitMq message from producer!!!!!!!!!!";
while (in.hasNext()) {
msg = in.next();
channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
System.out.println("send message " + msg);
}
channel.close();
connection.close();
}
}
五、消费者
public class Consumer {
private static final String QUEUE_NAME = "TEST_QUEUE";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = RabbitMqConnectionUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msg = new String(body, "UTF-8");
System.out.println("receive " + msg);
}
};
channel.basicConsume(QUEUE_NAME, true, defaultConsumer);
}
}
六、结果
可在控制台中查看打印的消息,也可在打开localhost:15672,账号密码初始为guest

登录后查看相关数据统计

3286

被折叠的 条评论
为什么被折叠?



