RabbitMQ最简单例子

主要步骤:

  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));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值