RabbitMQ最简单例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxg117/article/details/82660277

主要步骤:

  1. 创建Exchange
  2. 创建Queue
  3. 使用RoutingKey绑定Exchange到Queue
  4. 向Exchange发送消息,需要设置消息的RoutingKey
  5. Exchange收到消息后根据RoutingKey绑定转发消息到Queue
  6. 从Queue读取消息

Maven依赖:

<dependency>
    <groupId>org.springframework.amqp</groupId>
    <artifactId>spring-rabbit</artifactId>
    <version>1.7.2.RELEASE</version>
</dependency>

使用amqp-client,ConnectionFactory->Connection->Channel。使用Channel声明Exchange,Queue,并通过RoutingKey绑定Queue到Exchange。使用channel发送和接收消息。

public static void main(String[] args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    factory.setPort(5672);
    Connection cn = factory.newConnection();
    Channel channel = cn.createChannel();
    String exchange = "TestExchange";
    String routingKey = "TestRoutingKey";
    String queue = channel.queueDeclare().getQueue();
    channel.exchangeDeclare(exchange, "direct");
    channel.queueBind(queue, exchange, routingKey);

    channel.basicConsume(queue, new DefaultConsumer(channel){
        @Override
        public void handleDelivery(String tag, Envelope envelope, BasicProperties props, byte[] body)
                throws IOException {
            System.out.println("Received: " + new String(body));
        }
    });

    System.out.println("Sending.");
    channel.basicPublish(exchange, routingKey, null, "Hello".getBytes());

    Thread.sleep(100);

    channel.exchangeDelete(exchange);
    cn.close();
}

如果使用Spring,RabbitTemplate,大致流程如下:

public static void main(String[] args) throws Exception {
    ConnectionFactory connectionFactory = new CachingConnectionFactory("127.0.0.1", 5672);
    String exchange = "TestExchange2";  
    String routingKey = "TestRoutingKey2";
    String queue = "TestQueue2";

    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    admin.declareQueue(new Queue(queue));
    admin.declareExchange(new DirectExchange(exchange));
    admin.declareBinding(BindingBuilder.bind(new Queue(queue)).to(new DirectExchange(exchange)).with(routingKey));

    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.setExchange(exchange);

    template.convertAndSend(routingKey, "Hello");
    System.out.println("Received: " + template.receiveAndConvert(queue));
}

猜你喜欢

转载自blog.csdn.net/hxg117/article/details/82660277
今日推荐