在调度程序 websocket 中使用 stomp 的 Spring 引导推送动态消息



我尝试使用springboot(websocket(制作聊天机器人,我想知道是否可以在调度程序中推送动态消息,我需要一些帮助,我无法摆脱它。 我想在调度程序配置中推送消息,我该怎么做:

@EnableScheduling
@Configuration
public class SchedulerConfig {
@Autowired
SimpMessagingTemplate template;
@Scheduled(fixedDelay = 3000)
public void sendAdhocMessages() {
template.convertAndSend("/topic/user", new UserResponse("Fixed Delay Scheduler"));
}
}

在 sendAdhocMessages 方法中,我想传递一条将在 html 页面中显示的消息。 在官方文档中,不可能将参数传递给由@Scheduled注释的方法,有没有方法可以做到这一点?

官方文档包含有关如何将值传递给调度方法的提示。也许你可以提供一个充当消息提供者的 bean。在调度程序类中,自动连接消息提供程序并请求消息。 一个简短的代码示例:

@Componet
public class MessageProvider {
private String message;
// getter and setter ...
}

在调度程序中,可以使用消息提供程序,如下所示:

@EnableScheduling
@Configuration
public class SchedulerConfig {
@Autowired
SimpMessagingTemplate template;
@Autowired
MessageProvider messageProvider;
@Scheduled(fixedDelay = 3000)
public void sendAdhocMessages() {
String currentMessage = messageProvider.getMessage();
template.convertAndSend("/topic/user", new UserResponse(currentMessage));
}
}

最新更新