scala + amqp の I/F 悩み中
結果を全て Either で返すと仮定すると下記となる
(connect(host = "localhost", username = "guest", password = "guest") { conn =>
conn.channel { ch =>
for {
ex <- ch.declareExchange(name = "test.exchange", type = "direct").right
q <- ch.declareQueue(name = "test.queue").right
br <- q.bind(exchange = ex, routingKey = "test").right
pr <- ex.publish(routingKey = "test", payload = "Hello world!".getBytes).right
} yield pr
}
}) match {
case Left(e) => println(e.getMessage)
case _ =>
}
失敗は全て Exception で返すと仮定すると下記となる
try {
connect(host = "localhost", username = "guest", password = "guest") { conn =>
conn.channel { ch =>
val ex = ch.declareExchange(name = "test.exchange", type = "direct")
val q = ch.declareQueue(name = "test.queue")
q.bind(exchange = ex, routingKey = "test")
ex.publish(routingKey = "test", payload = "Hello world!".getBytes)
}
}
} catch {
case e: Exception => println(e.getMessage)
case _ =>
}
見た目も使い勝手も変わらない気がする。Scala は、どちらの記述もサポートしているので、どちらを採用するのが良いのか、さっぱり解らない。
9 months ago