6.RabbitMQ Topics

#  代表多个字符,例:a.#  a.abc123  a.2 a.22 等以a.开头的字符串均可匹配

*  代表一个单词,例: a.*  a.abc   a.1 a.a1均可匹配

 

 

package com.study.soufang.rabbit.a001.topic;

public class ConstantOfTopic {

    public static final String QUEUE_NAME_A = "logs_topic_queue_a";
    
    public static final String QUEUE_NAME_B = "logs_topic_queue_b";
    
    public static final String QUEUE_NAME_C = "logs_topic_queue_c";
    
    public static final String EXCHANGE_NAME="logs_topics";
    
    public static final String EXCHANGE_TYPE_FANOUT="fanout";
    
    public static final String EXCHANGE_TYPE_ROUTING="direct";
    
    public static final String EXCHANGE_TYPE_TOPICS="topic";
}
 

 

package com.study.soufang.rabbit.a001.topic;

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

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.study.soufang.rabbit.a001.RabbitChannelUtil;

import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class MyConsumer extends DefaultConsumer {

    
    public MyConsumer(Channel channel) {
        super(channel);
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
            throws IOException {
        try {
            String message = new String(body, "UTF-8");
            System.out.println(consumerTag+"--"+Thread.currentThread().getName()+" [x] Received '" + message + "'");
        } finally {
            /**
             * deliveryTag:该消息的index
                multiple:是否批量.true:将一次性ack所有小于deliveryTag的消息。
             */
            getChannel().basicAck(envelope.getDeliveryTag(), false);
            /*try {
                RabbitChannelUtil.closeChannel(getChannel());
            } catch (TimeoutException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/
        }
    }

}
 

package com.study.soufang.rabbit.a001.topic;

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

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.study.soufang.rabbit.a001.RabbitChannelUtil;

public class Recv {

    public static void doRecv(String queue,String routingKey) throws IOException, TimeoutException{
        Channel channel = null;
        try {
            channel = RabbitChannelUtil.createChannel();
            //声明交换机
            channel.exchangeDeclare(ConstantOfTopic.EXCHANGE_NAME, ConstantOfTopic.EXCHANGE_TYPE_TOPICS);
            //声明队列
            channel.queueDeclare(queue, false, false, false, null);
            //绑定队列到交换机
            channel.queueBind(queue, ConstantOfTopic.EXCHANGE_NAME, routingKey);
            Consumer consumer = new MyConsumer(channel);
            boolean autoAck = false;
            channel.basicConsume(queue, autoAck, consumer);
            channel.basicQos(1);
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws IOException, TimeoutException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    doRecv(ConstantOfTopic.QUEUE_NAME_A,"error.*.*");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    doRecv(ConstantOfTopic.QUEUE_NAME_B,"error.#");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    doRecv(ConstantOfTopic.QUEUE_NAME_C,"error.*");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }
    
}
 

package com.study.soufang.rabbit.a001.topic;

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

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.study.soufang.rabbit.a001.RabbitChannelUtil;
import com.study.soufang.rabbit.a001.PublishAndSubscribe.ConstantOfPublish;

public class Send {

    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = null;
        try {
            channel = RabbitChannelUtil.createChannel();
            //声明交换机
            channel.exchangeDeclare(ConstantOfTopic.EXCHANGE_NAME, ConstantOfTopic.EXCHANGE_TYPE_TOPICS);
            //发送消息,注意:需要消费者先启动并声明队列及绑定到此交换机,不然消息会丢失
            for(int i=0;i<100;i++){
                String message = "log---"+i;
                String routingKey = null;
                if(i%9==0){
                    routingKey = "error.a";
                }if(i%7==0){
                    routingKey = "error.b.c";
                }else{
                    routingKey = "error.abc";
                } 
                channel.basicPublish(ConstantOfTopic.EXCHANGE_NAME, routingKey, null, message.getBytes());;
                Thread.sleep(1);
            }
        } catch (IOException | TimeoutException | InterruptedException e) {
            e.printStackTrace();
        }finally{
            RabbitChannelUtil.closeChannel(channel);
        }
        
    }
}
 

 

package com.study.soufang.rabbit.a001;

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

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

public class RabbitChannelUtil {

    private final static String RABBIT_HOST= "192.168.10.22";
    private final static int RABBIT_PORT=5672;
    
    public static Channel createChannel() throws IOException, TimeoutException{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(RABBIT_HOST);
        factory.setPort(RABBIT_PORT);
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("helloworld");
        Connection connection = null;
        Channel channel = null;
        connection = factory.newConnection();
        channel = connection.createChannel();
        return channel;
    }
    /**
     * 关闭连接后不会再监听
     * @param channel
     * @throws IOException
     * @throws TimeoutException
     */
    public static void closeChannel(Channel channel) throws IOException, TimeoutException{
        Connection connection = channel.getConnection();
        if(null != channel){
            channel.close();
        }
        if(null != connection){
            connection.close();
        }
    }
    
}
 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当面试涉及RabbitMQ时,以下是一些常见的问题和答案,可以帮助你做好准备: 1. RabbitMQ是什么?它有什么用途? RabbitMQ是一个开源的消息队列中间件,用于实现应用程序之间的异步通信。它可以处理大量的消息,并提供了可靠的消息传递机制,用于构建分布式系统、任务调度、日志处理等。 2. RabbitMQ与其他消息队列中间件的区别是什么? RabbitMQ基于AMQP标准,具有丰富的功能和灵活性。相比其他消息队列中间件,如Kafka和ActiveMQ,RabbitMQ更适合需要可靠性和消息顺序保证的场景。 3. RabbitMQ中的术语有哪些? RabbitMQ包含以下术语: - 生产者(Producer):将消息发送到队列的应用程序。 - 消费者(Consumer):从队列中获取并处理消息的应用程序。 - 队列(Queue):存储消息的地方,生产者发送消息到队列,消费者从队列中获取消息。 - 交换机(Exchange):接收来自生产者的消息,并将它们路由到队列。 - 绑定(Binding):定义交换机和队列之间的关系,决定了如何将消息路由到特定队列。 4. RabbitMQ如何确保消息的可靠性? RabbitMQ通过持久化消息和确认机制来确保消息的可靠性。持久化消息可以在服务重启后仍然存在,而确认机制可以确保消费者成功处理消息后才将其从队列中删除。 5. RabbitMQ有哪些常见的消息模式? 常见的消息模式包括:点对点模式(Point-to-Point)、发布/订阅模式(Publish/Subscribe)、工作队列模式(Work Queues)和主题模式(Topics)。 这些问题只是作为参考,你可能还会面试到其他方面的问题。建议你对RabbitMQ的基本概念、特性和使用方法进行深入了解,并在实际项目中多进行实践,以便更好地回答面试问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值