RabbitMQ-Java实现Topic主题模式

主题模式

队列需要有一个routingKey与交换机exchange相匹配,此时交换机的type为topic

通过*(只匹配一个单词)或是#(可以匹配多个单词)匹配对应的队列

新建连接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();
    }
}

新建生产者类TopicSend 分别发送 orange.add 和 lazy.pink.rabbit

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

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

public class TopicSend {
    private final static String EXCHANGE_NAME = "Topic_exchange";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection = utils.getConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME,"topic");
        //声明key
        //String routingKey="orange.add";
        String routingKey="lazy.pink.rabbit";

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

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

    }
}

消费者1接受orange.* 的所有消息

import com.rabbitmq.client.*;

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

public class TopicReceive_1 {
    private final static String QUEUE_NAME = "Topic_queue_1";
    private final static String EXCHANGE_NAME = "Topic_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,"orange.*");
        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);
    }
}

消费者2分别可以接受 *.*.rabbit 或是lazy.#的所有消息

import com.rabbitmq.client.*;

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

public class TopicReceive_2 {
    private final static String QUEUE_NAME = "Topic_queue_2";
    private final static String EXCHANGE_NAME = "Topic_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);
        //绑定多个key
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"lazy.#");
        //channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"*.*.rabbit");
        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);//假设消费者2处理时间为1s
                } 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-five-java.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值