CDI context in Kafka de-/serializer in Quarkus app

老子叫甜甜 提交于 2021-02-10 09:24:54

问题


I have a Quarkus project with Smallrye reactive messaging based on Kafka. Since I want to work with a "complex pojo" I need a custom de-/serializer.

I'd like to make those two classes CDI beans so I can inject and use my custom logger, which is a CDI bean. Is there a way to achieve this?


Right now my injected logger object is simply null:

import org.apache.kafka.common.serialization.Serializer;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class MySerializer implements Serializer<MyDto>
{
    @Inject MyLogger logger;

    @Override public byte[] serialize(String topicName, MyDto myDto)
    {
        // this causes a java.lang.NullPointerException
        logger.info("serializing");

        ...
    }
}

回答1:


As far as I know, you can only register a class name with kafka, and it will create that class internally, ie. without using CDI.

Possible workaround: make the registered object a thin wrapper around the CDI-bean, and delegate the work to the bean:

public class MySerializer implements Serializer<MyDto> {
    private MySerializerCdi delegate;

    public MySerializer() {
        delegate = CDI.current().select(MySerializerCdi.class).get();
    }

    @Override public byte[] serialize(String topicName, MyDto myDto) {
        return delegate.serialize(topicName, myDto);
    }
    ...
}

... and rename your original CDI class accordingly.



来源:https://stackoverflow.com/questions/62577724/cdi-context-in-kafka-de-serializer-in-quarkus-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!