栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot实现websocket订阅消息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot实现websocket订阅消息

POM文件增加:


    org.springframework.boot
    spring-boot-starter-websocket

Websocket配置类:(放到config目录下,没有他的话,前端会订阅会失败)

package com.sa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

Websocket类:(其中@ServerEndpoint("/websocket/businessName/{clientName}")是前端使用的消息订阅链接,可以根据自身业务更换。我在写的时候把这个链接做成了免登录可用,可以根据实际情况自行决定)

package com.sa.common;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hstech.redis.RedisCache;
import com.hstech.util.common.spring.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;


@Component
@ServerEndpoint("/websocket/businessName/{clientName}")
public class WebSocket {

	private Session session;

	private static CopyOnWriteArraySet webSockets = new CopyOnWriteArraySet<>();

	@onOpen
	public void onOpen(Session session) {
        // 当前端订阅时,执行这个方法
		this.session = session;
		webSockets.add(this);
		System.out.println("【websocket消息】有新的连接,总数为:" + webSockets.size());
	}

	@onClose
	public void onClose() {
        // 当有订阅的页面关闭时,执行这个方法
		webSockets.remove(this);
		System.out.println("【websocket消息】连接断开,总数为:" + webSockets.size());
	}

	@onMessage
	public void onMessage(String message) {
        // 当前端主动发送消息时,订阅这个方法
		System.out.println("【websocket消息】收到客户端消息:" + message);
	}


	public void sendMessageLikeName(String clientName, String message) {
		// 自定义方法,根据订阅名匹配发送
        JSonObject msg = new JSonObject();
		msg.put("msgType", clientName);
		msg.put("msg", message);
		webSockets.forEach(webSocket -> webSocket.session.getAsyncRemote().sendText(msg.toJSonString()));
	}
}

当想要发送消息时,使用如下代码:

// 根据情况也可以换成@Resource注入形式
WebSocket webSocket = SpringUtil.getBean(WebSocket.class);
// 调用自定义的根据名称匹配发送,其中clientName为前端订阅时发送过来的名
webSocket.sendMessageLikeName(clientName,message);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号