交换机绑定的RoutingKey不同,只给某个队列发消息
多重绑定:绑定同一个队列的RoutingKey不同
// 生产者
import cn.soldat.utils.RabbitMqUtils
import com.rabbitmq.client.BuiltinExchangeType
import java.util.*
object DirectLogs {
const val EXCHANGE_NAME = "direct_logs"
}
fun main() {
val channel = RabbitMqUtils.getChannel()
channel.exchangeDeclare(DirectLogs.EXCHANGE_NAME, BuiltinExchangeType.DIRECT)
val scanner = Scanner(System.`in`)
while (scanner.hasNext()){
val message = scanner.next()
channel.basicPublish(DirectLogs.EXCHANGE_NAME, "error", null, message.toByteArray())
println("生产者发出消息: $message")
}
}
//消费者1
import cn.soldat.utils.RabbitMqUtils
import com.rabbitmq.client.BuiltinExchangeType
import com.rabbitmq.client.CancelCallback
import com.rabbitmq.client.DeliverCallback
object ReceiveLogsDirect01 {
const val EXCHANGE_NAME = "direct_logs"
}
fun main() {
val channel = RabbitMqUtils.getChannel()
// 声明交换机 Direct
channel.exchangeDeclare(ReceiveLogsDirect01.EXCHANGE_NAME, BuiltinExchangeType.DIRECT)
// 声明队列
channel.queueDeclare("console", false, false, false, null)
//绑定交换机与队列
channel.queueBind("console", ReceiveLogsDirect01.EXCHANGE_NAME, "info")
channel.queueBind("console", ReceiveLogsDirect01.EXCHANGE_NAME, "warning")
// 接收消息
val deliverCallback = DeliverCallback{ _,message ->
println("ReceiveLogsDirect01 控制台打印接收到的消息: ${String(message.body)}")
}
// 消费者取消消息时
channel.basicConsume("console", true, deliverCallback, CancelCallback {})
}
// 消费者2
import cn.soldat.utils.RabbitMqUtils
import com.rabbitmq.client.BuiltinExchangeType
import com.rabbitmq.client.CancelCallback
import com.rabbitmq.client.DeliverCallback
object ReceiveLogsDirect02 {
const val EXCHANGE_NAME = "direct_logs"
}
fun main() {
val channel = RabbitMqUtils.getChannel()
// 声明交换机 Direct
channel.exchangeDeclare(ReceiveLogsDirect02.EXCHANGE_NAME, BuiltinExchangeType.DIRECT)
// 声明队列
channel.queueDeclare("disk", false, false, false, null)
//绑定交换机与队列
channel.queueBind("disk", ReceiveLogsDirect02.EXCHANGE_NAME, "error")
// 接收消息
val deliverCallback = DeliverCallback{ _,message ->
println("ReceiveLogsDirect02 控制台打印接收到的消息: ${String(message.body)}")
}
// 消费者取消消息时
channel.basicConsume("disk", true, deliverCallback, CancelCallback {})
}
标签:六大,NAME,val,EXCHANGE,--,模式,import,message,channel
From: https://blog.51cto.com/soldatyxd/8305294