我的应用程序成功发送了Kafka消息,但仅在初始化Kafka之后。在此之前,我收到错误消息“调度程序没有订阅者”。如何等待订户完成频道注册?
以下是事件顺序的跟踪信息(以秒为单位计时):
我不确定该如何处理。大胆的猜测包括:
创建了一个新应用,使其变得尽可能简单
public interface Source {
@Output(channelName)
MessageChannel outboundChannel();
}
@EnableBinding(Source.class)
@Component
public class Sender {
@Autowired
private Source source;
public boolean send(SomeObject object) {
return source.outboundChannel().send(MessageBuilder.withPayload(object).build());
}
@Service
public class Scheduler {
@Autowired
Sender sender;
@Autowired
ThreadPoolTaskScheduler taskScheduler;
@PostConstruct
public void initialize() {
taskScheduler.schedule(new PollingTask(), nextTime);
}
private class PollingTask implements Runnable {
@Override
public void run() {
List<SomeObject> objects = getDummyData();
for(SomeObject object : objects)
{
sender.send(interval);
}
Instant nextTime = Instant.now().plusMillis(1_000L);
try {
taskScheduler.schedule(new PollingTask(), nextTime);
} catch (Exception e) {
logger.error(e);
}
}
}
编辑以添加解决方案
现在可以使用!在启动发送消息的事物的调度程序中,我从@PostConstruct的事物切换为SmartLifecycle :: start()。
@Service
public class Scheduler implements SmartLifecycle {
@Autowired
Sender sender;
@Autowired
ThreadPoolTaskScheduler taskScheduler;
@Override
public void start() {
taskScheduler.schedule(new PollingTask(), nextTime);
}
private class PollingTask implements Runnable {
@Override
public void run() {
List<SomeObject> objects = getDummyData();
for(SomeObject object : objects)
{
sender.send(interval);
}
Instant nextTime = Instant.now().plusMillis(1_000L);
try {
taskScheduler.schedule(new PollingTask(), nextTime);
} catch (Exception e) {
logger.error(e);
}
}
}
答案 0 :(得分:0)
@PostConstruct太早发送消息了;仍在构建上下文。.隐含SmartLifecycle,将bean置于较高阶段(Integer.MAX_VALUE),然后在start()中进行发送。
或者在ApplicationRunner中进行发送。