(代码)springboot webscoket 定时发送消息

代码

创建WebSocket端点
@ServerEndpoint(value = "/websocket/{uuid}")
@Component
public class MessageHandleController{

    private static final Logger logger = LoggerFactory.getLogger(MessageHandleController.class);

    //concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketController对象。
    public static CopyOnWriteArraySet<MessageHandleController> webSocketSet = new CopyOnWriteArraySet<>();

    // 使用ConcurrentHashMap来存储用户ID和WebSocket会话对象的映射。
    private static ConcurrentHashMap<String, MessageHandleController> webSocketMap = new ConcurrentHashMap<>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    private String uuid;

    @OnOpen
    public void onOpen(@PathParam("uuid") String uuid, Session session) {
        logger.info("uuid: {}, sessionId: {}", uuid, session.getId());
        // 将新建立的会话添加到webSocketMap中
        try {
            if (webSocketMap.containsKey(uuid)) {
                //如果有旧连接就先断开
                webSocketMap.get(uuid).session.close();
                webSocketSet.remove(webSocketMap.get(uuid));
            }
            this.session = session;
            this.uuid = uuid;
            webSocketSet.add(this); //加入set中
            webSocketMap.put(uuid, this); //加入map中
            // 其他代码...
        } catch (Exception e) {
            logger.error("error:" + e.getMessage());
        }
    }

    @OnClose
    public void onClose(@PathParam("uuid") String uuid, Session session) {
        // 当会话关闭时,从webSocketSet中移除该会话
        webSocketSet.remove(this);
        // 当会话关闭时,从webSocketMap中移除该会话
        webSocketMap.remove(uuid);
    }

    // 收到客户端消息后调用的方法
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("Message from client: " + message);
    }

    // 发生错误时调用
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("error:" + error.getMessage());
        try {
            session.close();
            // 当会话关闭时,从webSocketSet中移除该会话
            webSocketSet.remove(this);
            // 当会话关闭时,从webSocketMap中移除该会话
            webSocketMap.remove(this.uuid);
        } catch (IOException e) {
            logger.error("error:" + e.getMessage());
        }
    }

    public void sendMessage(Session session, String msg) {
        logger.info("发送消息");
        try {
            //判断当前人员是否连接websocket
            if (session.isOpen()) {
                session.getAsyncRemote().sendText(msg);
            } else {
                session.close();
                webSocketSet.remove(this); //从set中删除
                webSocketMap.remove(this.uuid); //从map中删除
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static CopyOnWriteArraySet<MessageHandleController> getWebSocketSet() {
        return webSocketSet;
    }

    public static void setWebSocketSet(CopyOnWriteArraySet<MessageHandleController> webSocketSet) {
        MessageHandleController.webSocketSet = webSocketSet;
    }

    public static ConcurrentHashMap<String, MessageHandleController> getWebSocketMap() {
        return webSocketMap;
    }

    public static void setWebSocketMap(ConcurrentHashMap<String, MessageHandleController> webSocketMap) {
        MessageHandleController.webSocketMap = webSocketMap;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
}

创建定时任务
@Scheduled(cron = "0 * * * * ?")
public void sendMsg() {
    logger.info("定时任务,start");
    CopyOnWriteArraySet<MessageHandleController> webSocketSet;
    try {
        webSocketSet = MessageHandleController.getWebSocketSet();
        webSocketSet.forEach(obj -> {
            logger.info("uuid:" + obj.getUuid());
            logger.info("session:" + obj.getSession().getId());
            obj.sendMessage(obj.getSession(), "time:" + LocalDateTime.now());
        });
    } catch (Exception e) {
        logger.error("error:" + e.getMessage());
    }
    logger.info("定时任务,end");
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
springboot websocket 心跳是为了保证连接的可持续性和稳定性而引入的一种机制。通过发送心跳消息,前后端可以相互检测连接是否正常,如果连接断开或无响应,则可以采取相应的措施进行重连或处理。 在Spring Boot中使用WebSocket实现心跳功能,首先需要引入相关依赖,如在pom.xml文件中添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 接下来,在application.yml文件中进行相关配置,如设置服务器端口和WebSocket相关参数。 然后,创建WebSocketConfig配置类,用于配置WebSocket的相关信息。 在后端代码中,可以使用定时任务来执行WebSocket的心跳检测。例如,可以创建一个WebSocketTask类,并使用@EnableScheduling注解启用定时任务功能。在该类中,可以编写定时任务方法,通过发送心跳消息来检测连接状态,并记录检测结果。 使用Spring Boot进行单元测试时,可以通过模拟发送心跳消息,来验证WebSocket的心跳功能是否正常工作。 总结起来,Spring Boot WebSocket心跳机制是通过配置和定时任务来实现的,通过定时发送心跳消息来检测连接状态,以保证连接的可持续性和稳定性。这样可以确保前后端交互的长连接能够正常运行。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot+WebSocket实战与心跳机制](https://blog.csdn.net/qq_42582773/article/details/127027514)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值