RabbitMQ的topic类型交换机

    xiaoxiao2021-03-25  95

    交换机类型为topic,可以使用通配符配置消息类型,#表示多个字符串,*表示1个字符。

    package topic; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class SendTopic { private static final String EXCHANGE_NAME = "topic_logs1"; public static void main(String[] args) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String msg="hello word!"; String msgType="fs.type01"; channel.basicPublish(EXCHANGE_NAME, msgType, null, msg.getBytes()); System.out.println(" [x] Sent '" + msgType + "':'" + msg + "'"); channel.close(); connection.close(); } } package topic; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.ConsumerCancelledException; import com.rabbitmq.client.QueueingConsumer; import com.rabbitmq.client.ShutdownSignalException; public class RecvTopic { private static final String EXCHANGE_NAME = "topic_logs1"; public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String queueName = channel.queueDeclare().getQueue(); // #代表0个或多个任意字符,*代表一个;#.type01可以匹配 fs.type01,也可以匹配 type01 channel.queueBind(queueName, EXCHANGE_NAME, "#.type01"); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); String routingKey = delivery.getEnvelope().getRoutingKey(); System.out.println(" [x] Received '" + routingKey + "':'" + message + "'"); } } }

    转载请注明原文地址: https://ju.6miu.com/read-14186.html

    最新回复(0)