Channel channel = connection.createChannel(); channel.exchangeDeclare("exchangeName", "direct"); //direct fanout topic channel.queueDeclare("queueName"); channel.queueBind("queueName", "exchangeName", "routingKey"); byte[] messageBodyBytes = "hello world".getBytes(); //需要绑定路由键 channel.basicPublish("exchangeName", "routingKey", MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
Fanout Exchange – 不处理路由键。你只需要简单的将队列绑定到交换机上。一个发送到交换机的消息都会被转发到与该交换机绑定的所有队列上。很像子网广播,每台子网内的主机都获得了一份复制的消息。Fanout交换机转发消息是最快的。
Channel channel = connection.createChannel(); channel.exchangeDeclare("exchangeName", "fanout"); //direct fanout topic channel.queueDeclare("queueName"); channel.queueBind("queueName", "exchangeName", "routingKey"); channel.queueDeclare("queueName1"); channel.queueBind("queueName1", "exchangeName", "routingKey1"); byte[] messageBodyBytes = "hello world".getBytes(); //路由键需要设置为空 channel.basicPublish("exchangeName", "", MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
Topic Exchange – 将路由键和某模式进行匹配。此时队列需要绑定要一个模式上。符号“#”匹配一个或多个词,符号“*”匹配不多不少一个词。因此“audit.#”能够匹配到“audit.irs.corporate”,但是“audit.*” 只会匹配到“audit.irs”。我在RedHat的朋友做了一张不错的图,来表明topic交换机是如何工作的:
Channel channel = connection.createChannel(); channel.exchangeDeclare("exchangeName", "topic"); //direct fanout topic channel.queueDeclare("queueName"); channel.queueBind("queueName", "exchangeName", "routingKey.*"); byte[] messageBodyBytes = "hello world".getBytes(); channel.basicPublish("exchangeName", "routingKey.one", MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);