Quarkus应用程序中的Kafka de-/serializer中的CDI上下文 [英] CDI context in Kafka de-/serializer in Quarkus app
问题描述
我有一个Quarkus项目,其中包含基于Kafka的Smallrye反应消息.由于我想使用复杂的pojo",我需要一个自定义的解串器/序列化器.
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.
我想制作这两个类的CDI bean,以便可以注入和使用我的自定义记录器,它是CDI bean.有没有办法做到这一点?
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?
现在,我注入的记录器对象只是null:
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");
...
}
}
推荐答案
据我所知,您只能在kafka中注册一个类名,它将在内部创建该类.无需使用CDI.
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.
可能的解决方法:将注册的对象做为CDI-bean的薄包装,然后将工作委托给Bean:
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);
}
...
}
...并相应地重命名您的原始CDI类.
... and rename your original CDI class accordingly.
这篇关于Quarkus应用程序中的Kafka de-/serializer中的CDI上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!