使用Springboot计划的websocket推送

Kon*_*ine 34 java spring push-notification websocket spring-boot

一般来说,我对弹簧靴和弹簧都有点新意.我被投入了一个项目,我的第一个"练习"是为了让我的脚湿透是在前端创建一个简单的新闻提要功能,它将通过websocket推送通知自动更新.

涉及的技术是:

  • Angular用于一般的前端应用程序
  • SockJS用于创建websocket通信
  • 踩踏webosocket以接收来自消息代理的消息
  • Springboot Websockets
  • Stomp Message Broker(java相关框架)

我想在前端实现的目标是:

  1. 加载视图时创建websocket连接
  2. 使用该websocket创建s stomp提供程序
  3. 让我的客户订阅它
  4. Catch服务器推送消息并更新角度视图

至于服务器端代码:

  1. 配置websocket东西并管理连接
  2. 让服务器每隔X个时间推送消息(通过执行程序或@Scheduled?).

我认为除了服务器端代码的最后部分之外,我已经实现了所有目标.我以下的示例在全双工模式下使用websocket,当客户端发送内容时,服务器立即响应消息队列并且所有订阅的客户端都更新.但我想要的是服务器本身发送一些东西Stomp而不等待客户端发出任何请求.

起初我创建了一个spring @Controller并使用@SendTo("/my/subscribed/path")注释添加了一个方法.但是我不知道如何触发它.我也尝试添加,@Scheduled但这个注释仅适用于具有void返回类型的方法(我正在返回一个NewsMessage对象).

基本上我需要的是让客户端初始化一个websocket连接,并在服务器开始按设定的时间间隔推送消息之后(或者每当触发一个事件时,它现在无关紧要).此外,每个新客户端都应该侦听相同的消息队列并接收相同的消息.

RMa*_*nik 38

首先,你需要websocket在春天启用它,然后确保你有相应的依赖关系pom.xml

例如最重要的一个:

         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

然后,您需要准备好配置.我建议你从简单的经纪人开始.

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/portfolio").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setApplicationDestinationPrefixes("/app");
        config.enableSimpleBroker("/topic", "/queue");
    }

}
Run Code Online (Sandbox Code Playgroud)

然后你的控制器应该是这样的.当您的AngularJs应用程序打开"/ portfolio"上的连接并向此频道发送订阅时,/topic/greeeting您将在控制器中收到此消息并回复所有订阅的用户.

@Controller
public class GreetingController {

    @MessageMapping("/greeting")
    public String handle(String greeting) {
        return "[" + getTimestamp() + ": " + greeting;
    }
}
Run Code Online (Sandbox Code Playgroud)

关于调度程序问题,您需要通过配置启用它:

@Configuration
@EnableScheduling
public class SchedulerConfig{}
Run Code Online (Sandbox Code Playgroud)

然后安排它:

@Component
public class ScheduledUpdatesOnTopic{

    @Autowired
    private SimpMessagingTemplate template;
    @Autowired
    private final MessagesSupplier messagesSupplier;

    @Scheduled(fixedDelay=300)
    public void publishUpdates(){
        template.convertAndSend("/topic/greetings", messagesSupplier.get());
    }
}
Run Code Online (Sandbox Code Playgroud)

希望以某种方式澄清概念和步骤,以使事情为你工作.

//注意:将@Scheduler更改为@Scheduled


Art*_*lan 7

首先,您无法在没有订阅的情况下向客户发送(推送)消息.

其次,要向所有订阅者发送消息,您应该查看topic抽象方面.

这是STOMP的基础.

我认为你很好@Scheduled,但你需要注入SimpMessagingTemplate以向STOMP经纪人发送消息以便随后推送.

另请参阅不提供brokerMessagingTemplate的Spring WebSockets XML配置

  • 虽然我使用了你的答案(我的项目已经使用了'SimpMessagingTemplate`来发送'logout'消息,我想在发布问题后使用它)我将另一个标记为正确,因为它可能对其他人更有帮助. (3认同)