springboot websocket后台主动推送消息

本文介绍了如何在SpringBoot应用中使用WebSocket实现后台主动向前端推送消息的功能。通过配置WebSocketConfig,创建Greeting和HelloMessage类,以及在启动类中使用messagingTemplate.convertAndSend方法,可以在后台轻松发送消息到前端。同时提供了index.js前端接收代码,并给出了源码的Git下载地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot,websocket,后台主动推送消息

1.pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.liuxl.cartmall</groupId>
	<artifactId>spring-websocket</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-websocket</name>
	<description>Demo project for Spring Boot
	https://spring.io/guides/gs/messaging-stomp-websocket/</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>

  <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </depende
### 使用 Spring Boot 和 WebSocket 实现定时推送消息 为了实现后台定时向客户端发送消息的功能,在Spring Boot应用中可以利用`@Scheduled`注解来设置定时任务,并结合WebSocket进行消息推送。 #### 添加依赖 首先,确保项目中的pom.xml文件包含了必要的依赖项[^2]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> ``` #### 配置WebSocket支持 接着配置WebSocket的支持。这一步骤可以通过创建一个配置类完成,该类需继承自`AbstractSessionWebSocketMessageBrokerConfigurer`并重写相应方法以启用STOMP协议和指定允许订阅的目的地前缀等操作[^1]。 #### 创建控制器处理消息收发逻辑 定义一个控制层组件负责接收来自前端的消息以及广播给所有已连接的客户机。这里展示了一个简单的例子,其中包含了一个用于响应特定路径下收到的信息的方法。 ```java import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class WebSocketController { @MessageMapping("/send") @SendTo("/topic/messages") public String handleMessage(String message) { return "Received: " + message; } } ``` #### 定义调度器执行周期性的消息推送 为了让应用程序能够在固定的时间间隔内自动触发并向所有的在线用户发送通知,则需要引入另一个Java Bean作为计划任务处理器。此bean内部维护着一个计数变量或者其他形式的数据源用来构建要传递的内容;同时它也持有一个指向simpMessagingTemplate实例的引用以便于调用convertAndSend()函数来进行实际的通知动作[^4]。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.web.socket.config.annotation.EnableScheduling; import org.springframework.messaging.simp.SimpMessagingTemplate; @Component @EnableScheduling public class MessageScheduler { private int count = 0; @Autowired SimpMessagingTemplate template; @Scheduled(fixedRate = 5000) public void reportCurrentTime() { this.template.convertAndSend("/topic/messages", "当前时间戳:" + System.currentTimeMillis()); ++count; // 可选:当达到一定次数后停止推流 if (this.count >= 10){ // 停止调度... } } } ``` 上述代码片段展示了如何每五秒一次将服务器端产生的最新数据(这里是简单地使用了系统毫秒级时间戳)分发出去。注意这里的`/topic/messages`应当与之前提到过的控制器里所监听的主题相匹配才能让信息成功抵达目标位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值