公众号merlinsea
rabbitmq的系统架构:
1、整体上看是基于C/S架构的中间件
2、在开发的时候要先部署好服务端,然后通过客户端去连接
3、客户端包括生产者和消费者,具体表现可以是java,python,c++等编程语言
简单队列模型【单个生产者,单个消费者】:
代码编写
1、引入rabbitmq的客户端依赖【引入依赖可以去maven仓库官网上找对应的包】
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.13.1</version> </dependency>
2、生产者代码
public class Send { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("39.107.221.166"); factory.setUsername("admin"); factory.setPassword("password"); factory.setVirtualHost("/dev"); factory.setPort(5672); //JDK7语法,自动关闭,创建连接 try (Connection connection = factory.newConnection()) { //创建信道 Channel channel = connection.createChannel(); /** * 队列名称 * 持久化配置:mq重启后还在 * 是否独占:只能有一个消费者监听队列;当connection关闭是否删除队列,一般是false,发布订阅是独占 * 自动删除: 当没有消费者的时候,自动删除掉,一般是false * 其他参数 * * 队列不存在则会自动创建,如果存在则不会覆盖,所以此时的时候需要注意属性 */ channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "hello world"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8)); System.out.println(" [x] Sent '" + message + "'"); } } }
3、消费者代码
public class Recv { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("39.107.221.166"); factory.setUsername("admin"); factory.setPassword("password"); factory.setVirtualHost("/dev"); factory.setPort(5672); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //一般是固定的,可以作为会话的名称 System.out.println("consumerTag="+consumerTag); //可以获取交换机、路由健等信息 System.out.println("envelope="+envelope); System.out.println("properties="+properties); System.out.println("body="+new String(body,"utf-8")); } }; //消费 channel.basicConsume(QUEUE_NAME,true,consumer); } }