锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. 如何在Spring Boot中实现实时通知

如何在Spring Boot中实现实时通知

0
  • 软件开发
  • 发布于 2024-08-17
  • 0 次阅读
黄健
黄健

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

如何在 Spring Boot 中实现实时通知

大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统 3.0 的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将讨论如何在 Spring Boot 应用中实现实时通知功能,这在现代 Web 应用程序和服务中是非常重要的一部分。

一、什么是实时通知?

实时通知是指系统能够即时将特定信息或事件推送给用户或其他系统的能力。与传统的轮询或定时拉取相比,实时通知能够实现更低的延迟和更高的实时性,为用户提供更好的交互体验。

二、实现实时通知的技术选择

在 Spring Boot 中,我们可以选择多种技术来实现实时通知,包括但不限于:

  1. WebSocket:提供了双向通信的能力,适用于需要低延迟、高实时性的场景。
  2. Server-Sent Events (SSE):允许服务器端向客户端单向推送数据,适用于单向通信场景。
  3. 消息队列:如 RabbitMQ、Kafka 等,用于异步消息传递和广播通知。
  4. Webhooks:通过 HTTP 回调实现事件通知,适用于接收外部系统的事件推送。

本文将重点介绍 WebSocket 和 SSE 的实现方式。

三、使用 WebSocket 实现实时通知

WebSocket 是一种先进的通信协议,允许在单个 TCP 连接上进行全双工通信。在 Spring Boot 中,我们可以通过 Spring WebSocket 模块实现 WebSocket 功能。

1. 添加依赖

首先,在pom.xml中添加 Spring WebSocket 的依赖:

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

2. 创建 WebSocket 配置类

package cn.juwatech.config;

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 configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic"); // Enable a simple in-memory message broker to carry messages back to the client on destinations prefixed with "/topic"
        config.setApplicationDestinationPrefixes("/app"); // Message-handling methods (message-handling methods) are mapped to the /app prefix
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS(); // Use SockJS to enable fallback options for browsers that don’t support websocket
    }
}

3. 编写控制器

package cn.juwatech.controller;

import cn.juwatech.dto.Notification;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class NotificationController {

    @MessageMapping("/sendNotification")
    @SendTo("/topic/notification")
    public Notification sendNotification(Notification notification) {
        return notification;
    }
}

4. 编写前端页面(HTML + JavaScript)

<!DOCTYPE html>
<html>
<head>
    <title>Real-time Notifications</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
    <script>
        var stompClient = null;

        function connect() {
            var socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/notification', function(notification) {
                    showNotification(JSON.parse(notification.body).message);
                });
            });
        }

        function showNotification(message) {
            var notificationsDiv = document.getElementById('notifications');
            var p = document.createElement('p');
            p.textContent = message;
            notificationsDiv.appendChild(p);
        }

        window.onload = function() {
            connect();
        };
    </script>
</head>
<body>
    <h2>Real-time Notifications</h2>
    <div id="notifications"></div>
</body>
</html>

四、使用 Server-Sent Events (SSE) 实现实时通知

Server-Sent Events (SSE) 允许服务器端向客户端单向推送数据,适合于需要向客户端发送更新或通知的场景。

1. 创建 SSE 控制器

package cn.juwatech.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
public class SSEController {

    private final ExecutorService nonBlockingService = Executors.newCachedThreadPool();

    @GetMapping(value = "/sse/notification", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter serverSentEvents() {
        SseEmitter emitter = new SseEmitter();
        nonBlockingService.execute(() -> {
            try {
                emitter.send(SseEmitter.event().name("notification").data("New notification"));
                // Simulate sending notifications periodically
                Thread.sleep(3000);
                emitter.send(SseEmitter.event().name("notification").data("Another notification"));
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }
}

2. 前端页面

<!DOCTYPE html>
<html>
<head>
    <title>Server-Sent Events (SSE) Notifications</title>
</head>
<body>
    <h2>Server-Sent Events (SSE) Notifications</h2>
    <div id="notifications"></div>

    <script>
        var notificationsDiv = document.getElementById('notifications');
        var eventSource = new EventSource('/sse/notification');

        eventSource.onmessage = function(event) {
            var message = event.data;
            var p = document.createElement('p');
            p.textContent = message;
            notificationsDiv.appendChild(p);
        };

        eventSource.onerror = function(event) {
            console.error('EventSource error: ', event);
            eventSource.close();
        };
    </script>
</body>
</html>

五、总结

通过本文,我们详细介绍了在 Spring Boot 应用中实现实时通知的两种主要方式:WebSocket 和 Server-Sent Events (SSE)。WebSocket 适合双向通信和复杂的应用场景,而 SSE 适合单向通知和简单的推送场景。我们通过具体的代码示例演示了如何在 Spring Boot 中配置和使用这些技术,以及如何在前端页面接收和展示实时通知。希望本文对你理解和实现实时通知功能有所帮助!

微赚淘客系统 3.0 小编出品,必属精品!

标签: #Spring Boot 173 #软件开发 1171 #JAVA 991
相关文章

万字:支付“核心系统”详解 2024-11-02 15:33

专栏作者:隐墨星辰 \| 主编:陈天宇宙 这篇文章也尝试化繁为简,探寻支付系统的本质,讲清楚在线支付系统最核心的一些概念和设计理念。 虽然支付行业已经过了风头最劲的时光,但跨境支付仍然在蓬勃发展,每年依然有很多新人进入这个行业,这篇文章尝试为这些刚入行的新人提供一点帮助。 文章只介绍一些支付行业十几

资深支付架构师视角:实战从问题定义到代码落地的完整套路 2024-11-02 15:33

前言 今天从一个实际案例入手,介绍站在架构师的角度,如何识别并定义问题,提炼需求,技术方案选型,再到详细设计,最后利用AI的能力协助写出核心的代码,验证与调优。 解决问题存在一定的模式,也可以称之为框架,总结出自己的思考和解题框架,以后再碰到同类型的问题就可以如庖丁解牛一样容易。 很多年前,我写代码

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

设计模式第16讲——迭代器模式(Iterator) 2024-10-08 11:24

一、什么是迭代器模式 迭代器模式是一种行为型设计模式,它提供了一种统一的方式来访问集合对象中的元素,而不是暴露集合内部的表示方式。简单地说,就是将遍历集合的责任封装到一个单独的对象中,我们可以按照特定的方式访问集合中的元素。 二、角色组成 抽象迭代器(Iterator):定义了遍历聚合对象所需的方法

vue2路由和vue3路由区别及原理 2024-10-08 11:24

一、Vue2 与 Vue3 路由的区别 1. 创建路由实例方式的不同 Vue 2 中,通过 Vue.use() 注册路由插件,并通过 new VueRouter() 来创建路由实例。 import Vue from 'vue';import VueRouter from 'vue-router';i

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.