我正在学习Quarkus和响应消息。我正在尝试在两个组件之间传递消息。我发现的示例演示了具有已知数据集的流,这些流正在流传输或连续重复有效负载。 (例如,来自Kafka快速入门,它会不断生成新的随机数作为价格)
仅当业务逻辑中发生某些事件时,才需要在流上放置一个事件。有例子吗?
我确实在StackOverflow Is there any function in Quarkus to send message to Kafka上找到了这篇文章。但是,有两个问题:
我无法使用此表格。
更新: @iabughosh
谢谢。但是我仍然得到一个没有注入空值的Emitter。以下是相关的代码段:
mp.messaging.outgoing.ownercreated.connector=smallrye-kafka
mp.messaging.outgoing.ownercreated.topic=ownercreated
mp.messaging.outgoing.ownercreated.value.serializer=io.quarkus.kafka.client.serialization.JsonbSerializer
`public class Owner {
@Inject
@Channel("ownercreated")
private static Emitter<Owner> ownerCreatedChannel;
public void persist() {
Owner.ownerCreatedChannel.send(this);
}
}`
我也注入了实例var。
在@iabughosh的请求下更新#2-谢谢您的帮助!
package org.boosey;
import io.smallrye.reactive.messaging.annotations.Channel;
import io.smallrye.reactive.messaging.annotations.Emitter;
import java.util.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@ApplicationScoped
public class Owner {
private final Logger logger = Logger.getLogger(Owner.class.getName());
@Inject
@Channel("ownercreated")
private Emitter<Owner> ownerCreatedChannel;
public String name;
public String email;
public void persist() {
logger.info("IN PERSIST");
ownerCreatedChannel.send(this);
logger.info("SENT NEW OWNER");
}
}
application.properties:
mp.messaging.outgoing.ownercreated.connector=smallrye-kafka
mp.messaging.outgoing.ownercreated.topic=ownercreated
mp.messaging.outgoing.ownercreated.value.serializer=io.quarkus.kafka.client.serialization.JsonbSerializer
从Quarkus REST Resource类中调用Owner.persist方法。我已经验证在Owner.persist中收到了正确实例化的Owner对象。
@Path("/owner")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApplicationScoped
public class OwnerResource {
@POST
public Response create(Owner owner) {
owner.persist();
return Response.status(201).build();
}
}
答案 0 :(得分:2)
如果在application.properties文件中正确配置了一个outgoing
主题,那么您要做的就是像这样注入Emitter:
@Inject
@Channel("your-channel")
Emitter<String> outgoingChannel;
,然后在您的函数中可以调用:
outgoingChannel.send(msg);
您的频道在配置文件中的外观如下:
mp.messaging.outgoing.your-channel.topic=kafka-topic
更新: 将发射器(带有注释)代码移到OwnerResource,它应该可以正常工作。另外,如果您移动了该代码,也可以从所有者中删除@ApplicationScoped。这里发生的是Owner对象不是CDI创建的,这就是为什么它不注入任何其他对象。 问候。