RabbitMQ-Java实现Publish/Subscribe订阅模式

订阅模式

一个生成者,多个消费者,每个消费者有自己的队列,生产者没有直接把消息发到队列,而是发给了交换机exchange

适合场景举例:对于同一个消息,要发邮件,也要发短信,因此拆分成两个队列

 

新建连接RabbitMQ的工具类utils

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
 
import java.io.IOException;
import java.util.concurrent.TimeoutException;
 
public class utils {
    public  static Connection getConnection() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setVirtualHost("/vhost_zdy");
        factory.setUsername("username");
        factory.setPassword("password");
 
        return factory.newConnection();
    }
}

生产者类PubSubSend

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class PubSubSend {
    private final static String EXCHANGE_NAME = "PubSub_exchange";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection = utils.getConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME,"fanout");

        for(int i=0;i<50;i++)//发50条消息
        {
            String msg="msg"+i;
            channel.basicPublish(EXCHANGE_NAME, "", null, msg.getBytes());
            Thread.sleep(20);//假设每20ms发送一次消息
            System.out.println("send:"+ msg);
        }

        channel.close();
        connection.close();

    }
}

运行后在控制台exchange查看是否生成交换机

消费者PubSubReceive_1和PubSubReceive_2 

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class PubSubReceive_1 {
    private final static String QUEUE_NAME = "PubSub_queue_mail";
    private final static String EXCHANGE_NAME = "PubSub_exchange";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = utils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");
        channel.basicQos(1);//保证一次只分发一个\n" +
        System.out.println(" [1] Waiting for messages.");

        DefaultConsumer defaultConsumer= new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg = new String(body,"UTF-8");
                System.out.println("[1]receive:"+ msg);
                try {
                    Thread.sleep(2000);//假设消费者1处理时间为2s
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("[1]done:"+ msg);
                    //手动回执
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoack=false;
        channel.basicConsume(QUEUE_NAME,autoack,defaultConsumer);
    }
}
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class PubSubReceive_2 {
    private final static String QUEUE_NAME = "PubSub_queue_tel";
    private final static String EXCHANGE_NAME = "PubSub_exchange";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = utils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");
        channel.basicQos(1);//保证一次只分发一个\n" +
        System.out.println(" [2] Waiting for messages.");

        DefaultConsumer defaultConsumer= new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg = new String(body,"UTF-8");
                System.out.println("[2]receive:"+ msg);
                try {
                    Thread.sleep(1000);//假设消费者1处理时间为2s
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("[2]done:"+ msg);
                    //手动回执
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoack=false;
        channel.basicConsume(QUEUE_NAME,autoack,defaultConsumer);
    }
}

 

 

查看效果

更多详情请参考官方文档

https://www.rabbitmq.com/tutorials/tutorial-three-java.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值