DEV Community

Oleg Agafonov for SIP3

Posted on • Edited on

How to extend Vert.x EventBus API to save on serialization.

Alexey Soshin has a great blog post: Understanding Vert.x: Event Bus. In the blog post he explains how to extend MessageCodec interface and start sending objects via Event Bus without paying anything for serialization.

SIP3 is a monitoring and troubleshooting platform that has to handle hundreds of thousands SIP packets and millions of RTP packets per second. That's why we've started using this approach from the very beginning. However, as a Kotlin users, we couldn't do not add some sugar 🍬🍭🍰.

Here is our recipe:

🍬 Register MessageCodec

Let's use Kotlin method extensions to define our local codec:

fun Vertx.registerLocalCodec() {
    eventBus().unregisterCodec("local")
    eventBus().registerCodec(object : MessageCodec<Any, Any> {
        override fun decodeFromWire(pos: Int, buffer: Buffer?) = throw NotImplementedError()
        override fun encodeToWire(buffer: Buffer?, s: Any?) = throw NotImplementedError()
        override fun transform(s: Any?) = s
        override fun name() = "local"
        override fun systemCodecID(): Byte = -1
    })
}
Enter fullscreen mode Exit fullscreen mode

All is left is just to register our codec explicitly while initializing Vertx object.

🍭 Extend EventBus

Kotlin has two great features - method extensions and named arguments. We decided to use a combination of those to introduce a custom method called localSend:

object EventBusUtil {

    val USE_LOCAL_CODEC = deliveryOptionsOf(codecName = "local", localOnly = true)
}

fun EventBus.localSend(address: String, message: Any, options: DeliveryOptions? = null) {
    options?.apply {
        codecName = "local"
        isLocalOnly = true
    }
    send(address, message, options ?: USE_LOCAL_CODEC)
}
Enter fullscreen mode Exit fullscreen mode

🍰 Just enjoy

Now we can start sending messages within the application without paying for serialization:

fun main() {
    val vertx = Vertx.vertx()
    vertx.registerLocalCodec()

    val answer = BigDecimal(42)
    vertx.eventBus().localSend("question", answer)
}
Enter fullscreen mode Exit fullscreen mode

I hope you loved the approach and will start using it in your projects. If you have any questions, just leave me a message 😄

Happy coding...

Top comments (0)