Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codec registration with event bus on vert.x

Tags:

java

vert.x

Message codec example for vert.x event bus.

I have a use case where I want to register my custom object to send it on the event bus.For that,I have to implement Message codec class .I would like to know if more than one object can be registered under the same name with event bus?If not,what is the correct way of registering multiple custom objects as codec.

like image 896
JavaPython Avatar asked Sep 05 '25 03:09

JavaPython


1 Answers

If you're not using clustered EventBus, then you can just implement every codec like this:

class IdentityCodec implements MessageCodec {
    private final Class aClass;

    public IdentityCodec(Class aClass) {
        this.aClass = aClass;
    }

    @Override
    public void encodeToWire(Buffer buffer, Object o) {

    }

    @Override
    public Object decodeFromWire(int pos, Buffer buffer) {
        return null;
    }

    @Override
    public Object transform(Object o) {
        return o;
    }

    @Override
    public String name() {
        return aClass.getName() + "Codec";
    }

    @Override
    public byte systemCodecID() {
        return -1;
    }
}

The important part here is that every codec must have a unique name, so I'm generating it based on the class name.

Then register it as a default codec:

    vertx.eventBus().registerDefaultCodec(A.class, new IdentityCodec(A.class));
    vertx.eventBus().registerDefaultCodec(B.class, new IdentityCodec(B.class));

Probably there are nicer ways to generify it, but without seeing your code, it's impossible to tell.

like image 154
Alexey Soshin Avatar answered Sep 08 '25 05:09

Alexey Soshin