RabbitMQ简单队列

模型:
在这里插入图片描述
P:消息生产者
C:消费者
红色部分是消息队列

简单队列的使用
1、使用springboot,引入rabbitmq的依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
			<version>1.5.19.RELEASE</version>
		</dependency>

2、创建工具类获取连接

public class RabbitMqUtil {
	
	public static Connection getConnection() throws IOException, TimeoutException {
		//获取工厂,通过工厂创建连接
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("192.168.21.47");
		factory.setPort(5672);
		factory.setVirtualHost("/host1");
		factory.setUsername("admin");
		factory.setPassword("admin");
		
		Connection conn = null;
		conn = factory.newConnection();

		return conn;
	}
}

3、创建生产者

public class Provider {
	private static final String QUNUE_NAME="test_qunue";
	public static void main(String args[]) throws Exception {
		
		//获取rabbitMQ连接
		Connection conn = RabbitMqUtil.getConnection();
		//创建channel
		Channel channel = conn.createChannel();
		//创建队列声明
		channel.queueDeclare(QUNUE_NAME, false, false, false, null);
		//发送消息
		channel.basicPublish("", QUNUE_NAME, null, "hello world".getBytes());
		
		channel.close();
		conn.close();
	}
}

4、创建消费者

public class Reciver {
	private static final String QUNUE_NAME = "test_qunue";
	public static void main(String[] args) throws Exception {
		newApi();
	}

	public static void newApi()
			throws Exception {
		//获取连接
		Connection conn = RabbitMqUtil.getConnection();
		//创建channel
		Channel channel = conn.createChannel();
		//声明队列,如果生产者中声明了队列,消费者中可以不声明
		//channel.queueDeclare(QUNUE_NAME, false, false, false, null);
		//创建消费者
		Consumer consumer = new DefaultConsumer(channel) {
			//当生产者发送消息到rabbitmq之后,会自动触发消费者中的handleDelivery方法
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				String msg = new String(body,"UTF-8");
				System.out.println(msg);
			}
		};
		//监听队列
		channel.basicConsume(QUNUE_NAME, true, consumer);
	}

	/**
	 * 过期的方式
	 * @throws Exception
	 */
	public static void oldApi()
			throws Exception {
		Connection conn = RabbitMqUtil.getConnection();
		Channel channel = conn.createChannel();
		QueueingConsumer consumer = new QueueingConsumer(channel);
		channel.basicConsume(QUNUE_NAME, true, consumer);

		while (true) {
			Delivery delivery = consumer.nextDelivery();
			String msg = new String(delivery.getBody());
			System.out.println(msg);
		}
	}
}

简单队列模型耦合度高,生产者消费者一一对应,如果存在多个消费者,那么该模型则无法使用,队列名如果更改,那么消费者需要同步修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值