这里只提供消费者端的写法
首先加入 gradle依赖
// rabbit mq
implementation 'com.rabbitmq:amqp-client:4.4.1'
连接服务端并开启监听线程
private val mConnectionFactory = ConnectionFactory() // 声明ConnectionFactory对象
private fun setUpConnectionFactory() {
//建立连接
mConnectionFactory.apply {
host = edit_host?.text?.toString()
port = edit_port?.text?.toString()?.toInt()!!
username = edit_username?.text?.toString()
password = edit_password?.text?.toString()
connectionTimeout = 5000
}
thread = Thread {
LogUtils.d(TAG, "start connecting ...")
// 创建连接
val connection = mConnectionFactory.newConnection()
val channel = connection.createChannel()
//将队列绑定到消息交换机 exchange 上
val queueDeclare = channel.queueDeclare()
channel.queueBind(queueDeclare.queue,"log.fanout","fanout.sms")
//创建消费者
val consumer = QueueingConsumer(channel)
channel.basicConsume(queueDeclare.queue, true, consumer)
LogUtils.d(TAG, "start reading ...")
while (true) {
val delivery = consumer.nextDelivery()
val message = String(delivery.body)
LogUtils.d(TAG, message)
}
}
thread?.start()
}
下面介绍 Director 模式的写法
private val mConnectionFactory = ConnectionFactory() // 声明ConnectionFactory对象
private fun setUpConnectionFactory() {
mConnectionFactory.apply {
host = Constant.MQ.MQ_HOST
port = Constant.MQ.MQ_PORT
username = Constant.MQ.MQ_USERNAME
password = Constant.MQ.MQ_PASSWORD
connectionTimeout = 5000
}
val infoConnection = "host = ${mConnectionFactory.host}, port = ${mConnectionFactory.port}, username = ${mConnectionFactory.username}, password = ${mConnectionFactory.password}"
thread = Thread {
kotlin.runCatching {
LogUtils.d(TAG, "start connecting ${infoConnection}...")
// 创建连接
mConnection = mConnectionFactory.newConnection()
val channel = mConnection?.createChannel()
val exchange = "k12UserExchange"
val routingKey = "k12UserQueue_${SPRepository.INSTANCE.studentUserId}"
//将队列绑定到消息交换机 exchange 上
LogUtils.d(TAG, "start reading ... exchange = $exchange, routingKey = $routingKey")
channel?.exchangeDeclare(exchange, BuiltinExchangeType.DIRECT)
val queueName = channel?.queueDeclare()?.queue // 这个 queueName 也可以自己使用固定的名称
channel?.queueBind(queueName, exchange, routingKey)
val consumer = object : DefaultConsumer(channel) {
override fun handleDelivery(
consumerTag: String?,
envelope: Envelope?,
properties: AMQP.BasicProperties?,
body: ByteArray?
) {
super.handleDelivery(consumerTag, envelope, properties, body)
body?.let {
LogUtils.d(TAG, "handleDelivery ${String(body)}")
}
}
}
channel?.basicConsume(queueName,true,consumer)
LogUtils.d(TAG, "channel?.basicConsume")
}.onFailure {
LogUtils.e(TAG, "setUpConnectionFactory onFailure $it")
running = false
thread?.interrupt()
}
}
thread?.start()
}