2.rabbitmq入门demo

相关依赖jar

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>3.6.1</version>
</dependency>

生产者

public static void main(String[] args) throws Exception {
	//1创建连接工厂
	ConnectionFactory factory=new ConnectionFactory();
	factory.setHost("xxxxxx");
	factory.setPort(5672);
	factory.setVirtualHost("/");
	//2获取连接
	Connection connection = factory.newConnection();
	//3创建channer
	Channel channel = connection.createChannel();
	for (int i = 0; i < 5; i++) {
		//4 发送消息 不用指定队列名,默认交换机根据路由自动定位队列
		channel.basicPublish("", "test4", null, "111".getBytes());
	}
	//5关闭资源
	channel.close();
	connection.close();
}

消费者

public static void main(String[] args) throws Exception{
	//1创建连接工厂
	ConnectionFactory factory=new ConnectionFactory();
	factory.setHost("xxx");
	factory.setPort(5672);
	factory.setVirtualHost("/");
	//2获取连接
	Connection connection = factory.newConnection();
	//3创建channer
	Channel channel = connection.createChannel();
	//4创建队列
	channel.queueDeclare("test4", true, false, false, null);
	//5channer与队列进行连接获取消息
	QueueingConsumer queueingConsumer=new QueueingConsumer(channel);
	channel.basicConsume("test4", true, queueingConsumer);
	while (true) {
		Delivery delivery=queueingConsumer.nextDelivery();
		String msgString  =new String(delivery.getBody());
		System.out.println(msgString);
	}
}

执行顺序:先执行消费者创队列,再执行生产者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值