RabbitMQ--模型四的demo

    技术2024-08-10  83

    模型四

    路由键 -> 交换机和队列绑定若干路由键,发布的消息可以指定路由键发送

    提供者这边:Provide.Class

    //提供者 public class Provide { public static void main(String[] args) throws Exception { //连接RabbitMQ Connection connection = ConnectionUtil.getConnection(); //通过连接创建管道对象 Channel channel = connection.createChannel(); //创建交换机 channel.exchangeDeclare("test_exchange1", "direct"); //给队列发送消息 for(int i=1;i<=10;i++){ String info = "Hello RabbitMQ"+i; String routingKey = i % 3 == 0 ? "A" : "B"; channel.basicPublish("test_exchange1", routingKey, null,info.getBytes("utf-8")); } //关闭连接 connection.close(); } }

    消费者1:Consumer.Class

    //消费者1 public class Consumer { public static void main(String[] args) throws IOException { //连接RabbitMQ Connection connection = ConnectionUtil.getConnection(); //通过连接拿到管道对象 Channel channel = connection.createChannel(); //声明队列 channel.queueDeclare("test_queue1", false, false, false, null); //队列,交换机,路由键绑定,Consumer绑定A,B两个路由键 channel.queueBind("test_queue1", "test_exchange1", "A"); channel.queueBind("test_queue1", "test_exchange1", "B"); //监听队列 channel.basicConsume("test_queue1", true,new DefaultConsumer(channel){ @Override public void handleDelivery(java.lang.String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("接收到消息:"+new String(body,"utf-8")); } }); } }

    消费者2:Consumer2.Class

    //消费者2 public class Consumer2 { public static void main(String[] args) throws IOException { //连接RabbitMQ Connection connection = ConnectionUtil.getConnection(); //通过连接拿到管道对象 Channel channel = connection.createChannel(); //声明队列 channel.queueDeclare("test_queue2", false, false, false, null); //队列,交换机,路由键绑定,Consumer2只绑定B路由键 channel.queueBind("test_queue2", "test_exchange1", "B"); //监听队列 channel.basicConsume("test_queue2", true,new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("接收到消息:"+new String(body,"utf-8")); } }); } }

    工具类:ConnectionUtil.Class

    //工具类 public class ConnectionUtil { private static ConnectionFactory connectionFactory; static { //创建连接工厂,连接rabbitmq connectionFactory = new ConnectionFactory(); connectionFactory.setHost("192.168.xxx.xxx"); connectionFactory.setPort(5672); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); connectionFactory.setVirtualHost("/"); } public static Connection getConnection(){ Connection connection = null; try { connection = connectionFactory.newConnection(); } catch (Exception e) { e.printStackTrace(); } return connection; } }

     

    Consumer1打印的结果

    Consumer2打印的结果

    Processed: 0.019, SQL: 9