利用WebSocket实现实时通知

在编写小说网站时,突发奇想:作者发布章节后,是不是粉丝应该接收到作者发布章节的消息通知呢。以下就是一个测试案例:

添加pom.xml文件依赖:

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

以上只给了websocket依赖,实际还要添加mysql依赖,以及配置application中数据库:

XML 复制代码
spring.datasource.url=
spring.datasource.driver-class-name=
spring.datasource.username=
spring.datasource.password=

接下来就创建一个配置类启用 WebSocket 消息代理:

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 定义 WebSocket 端点,前端通过此连接
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*") // 允许跨域(生产环境建议限制域名)
                .withSockJS(); // 支持 SockJS 回退
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 客户端订阅地址前缀(前端从这里订阅)
        registry.enableSimpleBroker("/topic");
    }
}

监听作者发布章节事件

定义事件类

java 复制代码
public class ChapterPublishedEvent {
    private Long authorId;
    private String chapterTitle;

    // 构造方法、Getter/Setter
}
在发布章节的方法中触发事件
java 复制代码
@RestController
public class ChaptersController {

@Autowired
NovelsMapper mapper;

@Autowired
private ApplicationEventPublisher eventPublisher;

    @RequestMapping("chapter")
    String insert(HttpServletRequest request){
// 触发事件
        eventPublisher.publishEvent(new ChapterPublishedEvent(1, "文章名"));
        return "chapter:" + request.getServerPort();
    }
}

推送消息给关注者

监听事件并发送消息

java 复制代码
import com.lxy.other.dao.UserAuthMapper;
import com.lxy.other.vo.ChapterPublishedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async; // 可选异步
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class ChapterPublishListener {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private UserAuthMapper userAuthMapper; // 自定义服务,用于查询关注者

    @EventListener
    @Async // 异步处理(可选,需在启动类添加 @EnableAsync)
    public void handleChapterPublishedEvent(ChapterPublishedEvent event) {
        Long authorId = event.getAuthorId();
        // 查询所有关注该作者的用户的ID
        List<Long> followerIds = new ArrayList<>(Arrays.asList(2L, 3L));
        // 向每个关注者推送消息
        followerIds.forEach(followerId -> {
            String destination = "/topic/user/" + followerId + "/notifications";
            messagingTemplate.convertAndSend(destination, "作者发布了新章节:" + event.getChapterTitle());
        });
    }
}

前端订阅通知

使用 SockJSStomp.js 连接 WebSocket 并订阅频道:

html 复制代码
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <title>WebSocket通知</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.6.1/dist/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

<script>
    // 1. 连接 WebSocket
    const socket = new SockJS('http://127.0.0.1:8002/ws');
    const stompClient = Stomp.over(socket);

    // 2. 订阅通知
    stompClient.connect({}, () => {
        const userId = 2; // 替换为实际用户ID
        stompClient.subscribe(`/topic/user/${userId}/notifications`, (message) => {
            console.log('收到通知:', message.body);
            alert(message.body);
        });
    }, (error) => {
        console.error('连接失败:', error);
    });
</script>
</body>
</html>

效果图:

发送触发事件的请求。

这个时候就可以自定义 页面样式了

相关推荐
一 乐6 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
sunfove8 小时前
光网络的立交桥:光开关 (Optical Switch) 原理与主流技术解析
网络
期待のcode9 小时前
前后端分离项目 Springboot+vue 在云服务器上的部署
服务器·vue.js·spring boot
ProgramHan9 小时前
Spring Boot 3.2 新特性:虚拟线程的落地实践
java·jvm·spring boot
Kevin Wang72710 小时前
欧拉系统服务部署注意事项
网络·windows
min18112345610 小时前
深度伪造内容的检测与溯源技术
大数据·网络·人工智能
汤愈韬10 小时前
NAT策略
网络协议·网络安全·security·huawei
源码获取_wx:Fegn089511 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
汤愈韬11 小时前
Full Cone Nat
网络·网络协议·网络安全·security·huawei
毕设源码_郑学姐11 小时前
计算机毕业设计springboot基于HTML5的酒店预订管理系统 基于Spring Boot框架的HTML5酒店预订管理平台设计与实现 HTML5与Spring Boot技术驱动的酒店预订管理系统开
spring boot·后端·课程设计