mq使用replyto队列进行消息回复

消费者

import com.rabbitmq.client.*;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.shterm.test.ConnectionUtil;

import java.io.IOException;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyConsumer {
    private final static String QUEUE_NAME = "topic_queue_1";
    private final static String EXCHANGE_NAME = "topic_exchange";

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Consumer start.......");
        ExecutorService exe= Executors.newCachedThreadPool();
        for (int i=0;i<10;i++){
            Thread.sleep(2);
            exe.execute(()->work());
        }
    }

    public static void work(){
        try(Connection connection = ConnectionUtil.getConnection("127.0.0.1",5671,"/","test","test");){
            Channel channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"update.#");
            channel.basicQos(1);

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                           byte[] body) throws IOException {
                    AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                            .correlationId(properties.getCorrelationId()).build();
                    String response = "";
                    try {
                        response += "ok";
                    } catch (RuntimeException e) {
                        System.out.println(" [.] " + e.toString());
                    } finally {
                        // 返回处理结果队列
                        channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                        //  确认消息,已经收到后面参数 multiple:是否批量.true:将一次性确认所有小于envelope.getDeliveryTag()的消息。
                        channel.basicAck(envelope.getDeliveryTag(), false);
                        // RabbitMq consumer worker thread notifies the RPC
                        // server owner thread
                        synchronized (this) {
                            this.notify();
                        }
                    }
                }
            };
            channel.basicConsume(QUEUE_NAME,consumer);
            while (true) {
                synchronized (consumer) {
                    try {
                        consumer.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

生产者

import com.rabbitmq.client.*;
import com.shterm.test.ConnectionUtil;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Producer {

    private final static String EXCHANGE_NAME = "topic_exchange";

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exe = Executors.newFixedThreadPool(5);
        System.out.println("Producer start.......");
        while(true){
            Thread.sleep(1000);
            for(int i=0;i<130;i++){
                 exe.execute(() -> produce());
            }
        }

    }

    public static void produce() {
        try (Connection connection = ConnectionUtil.getConnection("127.0.0.1", 5671, "/", "test", "test");) {
            String replyQueueName;
            Channel channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_NAME, "topic");
            String corrId = UUID.randomUUID().toString();
            String message = "this is topic :" + corrId;
            replyQueueName = channel.queueDeclare().getQueue();
            synchronized (replyQueueName) {
                //发送请求消息,消息使用了两个属性:replyto和correlationId
                //服务端根据replyto返回结果,客户端根据correlationId判断响应是不是给自己的
                AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName)
                        .build();
                channel.basicPublish(EXCHANGE_NAME, "update.Name", props, message.getBytes());
                final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
                // String basicConsume(String queue, boolean autoAck, Consumer callback)
                channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                               byte[] body) throws IOException {
                        //检查它的correlationId是否是我们所要找的那个
                        if (properties.getCorrelationId().equals(corrId)) {
                            //如果是,则响应BlockingQueue
                            response.offer(new String(body, "UTF-8"));
                        }
                    }
                });
                channel.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值