Five thematic working mode of the RabbitMQ (Topic) mode

Five thematic working mode of the RabbitMQ (Topic) mode

The publish subscribe model, manufacturer dealing with Topic type switch, the switch sends the message to the queue corresponding to the binding, while a routing key, as the screening conditions, while fuzzy matching.

Import dependence

<!--RabbitMQ的依赖-->
<dependency>
  <groupId>com.rabbitmq</groupId>
  <artifactId>amqp-client</artifactId>
  <version>5.7.3</version>
</dependency>

First create tools for generating a connection, to avoid duplication of writing this code

public class RabbitMQUtil {
    private static ConnectionFactory factory = new ConnectionFactory();
    static{
        //用户名
        factory.setUsername("hello");
        //密码
        factory.setPassword("123456");
        //虚拟机
        factory.setVirtualHost("/myhost");
        //IP地址,运行rabbitmq组件的主机ip地址
        factory.setHost("192.168.31.14");
        //端口
        factory.setPort(5672);
    }

    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = factory.newConnection();
            return  connection;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Producers

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //获取连接
        Connection connection = RabbitMQUtil.getConnection();
        //创建通道
        Channel channel = connection.createChannel();
        /**
         * 声明交换机
         * 参数1:交换机名称
         * 参数2:交换机类型:fanout、direct、topic、headers
         */
        channel.exchangeDeclare("topic_exchange", BuiltinExchangeType.TOPIC);
        Map<String,String> map = new HashMap<>();
        map.put("001","重庆");
        map.put("002","成都");
        map.put("003","北京");
        map.put("004","乌鲁木齐");
        for (String key : map.keySet()) {
            // 参数2:路由key就是 数据筛选的条件
            channel.basicPublish("topic_exchange",key,null,map.get(key).getBytes());
        }
        channel.close();
        connection.close();
    }
}

consumer

public class Customer1{
    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtil.getConnection();
        //创建通道
        final Channel channel =connection.createChannel();
        //声明队列
        channel.queueDeclare("queue1",false,false,false,null);
        //绑定交换机和队列,设置路由key
        channel.queueBind("queue1","topic_exchange","001");
        channel.queueBind("queue1","topic_exchange","002");
        //签收消息:false表示手动编程的方式签收
        channel.basicConsume("queue1",false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("customer1接收到的消息:"+new String(body));
                //签收
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}
public class Customer2{
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtil.getConnection();
        final Channel channel =connection.createChannel();
        channel.queueDeclare("queue2",false,false,false,null);
        //匹配所有
        channel.queueBind("queue2","topic_exchange","*");
        channel.basicConsume("queue2",false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("customer2接收到的消息:"+new String(body));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

NOTE: Manufacturer Send message to the switch, in accordance with the key assigned to the appropriate queue, if the first test run where the consumer needs to ensure that the end switch is created, it needs to end consumers switch statement, the producer end of this time the switch does not need to declare Of course, if the end of the first run producer, the producer will need to end the first statement switch, this time the consumer end of the switch statement can not, in short, the body case specific analysis, flexibility, of course, in order to save, you can always declare.

Released seven original articles · won praise 0 · Views 42

Guess you like

Origin blog.csdn.net/zifan_/article/details/104765507