SprinngBoot下集成webSock的几种方式

SprinngBoot下集成webSock的几种方式

基于kafka配置推送

package cn.microvideo.flowac.sys.util;

import cn.microvideo.flowac.sys.entity.LocalSysMsgForWSBean;
import cn.microvideo.flowac.sys.entity.WSMsgModuleEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Description: WS工具类
 * @Author: xuwz
 * @Date: 2021/8/5 9:29
 */
@Component
public class WebSocketUtil {

    private static WebSocketUtil instance;

    // TODO 暂时使用kafkaOne对象,后续可能会更改为系统自己的kafka
    @Resource(name = "kafkaOneTemplate")
    private KafkaTemplate<String, Object> kafkaTemplate;
    @Value("${localSysMessageForWSTopic}")
    private String localSysMessageForWSTopic;

    /**
     * @Description 初始化
     * @Author xuwz
     * @Date 2021/8/5 19:45
     */
    @PostConstruct
    public void init() {
        instance = this;
    }

    /**
     * @Description 向全部连接发送
     * @Author xuwz
     * @Date 2021/8/5 20:24
     */
    public static void sendForWS(Object message, WSMsgModuleEnum moduleEnum) {
        LocalSysMsgForWSBean bean = createBean(message, moduleEnum, 0);
        instance.kafkaTemplate.send(instance.localSysMessageForWSTopic, GsonUtil.toJson(bean));
    }

    /**
     * @Description 向指定unit发送
     * @Author xuwz
     * @Date 2021/8/5 20:24
     */
    public static void sendForWSByUnit(Object message, WSMsgModuleEnum moduleEnum, String unitCode) {
        LocalSysMsgForWSBean bean = createBean(message, moduleEnum, 1);
        bean.setUnitCode(unitCode);
        instance.kafkaTemplate.send(instance.localSysMessageForWSTopic, GsonUtil.toJson(bean));
    }

    /**
     * @Description 向指定用户发送
     * @Author xuwz
     * @Date 2021/8/5 20:25
     */
    public static void sendForWSByUser(Object message, WSMsgModuleEnum moduleEnum, String userId) {
        LocalSysMsgForWSBean bean = createBean(message, moduleEnum, 2);
        bean.setUserId(userId);
        instance.kafkaTemplate.send(instance.localSysMessageForWSTopic, GsonUtil.toJson(bean));
    }

    /**
     * @Description 构建对象
     * @Author xuwz
     * @Date 2021/8/5 20:25
     */
    private static LocalSysMsgForWSBean createBean(Object message, WSMsgModuleEnum moduleEnum, Integer sendType) {
        LocalSysMsgForWSBean bean = new LocalSysMsgForWSBean();
        bean.setModule(moduleEnum.getModule());
        bean.setMessageType(moduleEnum.getMessageType());
        bean.setSendType(sendType);
        bean.setMessage(message);
        return bean;
    }

}

基于session配置推送

package com.microvideo.ewcp.configration;


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

/**
 * @Author:wlj
 * @Description:websocket配置类
 * @Date:2019-05-27
 */
@Configuration
public class WebSocketConfig {
	
	/**
	 * @Author:wlj
	 * @Description:获得服务端点提供者
	 * @Date:2019-05-27
	 */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
package  com.microvideo.ewcp.configration;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

/**
 * @Author: wlj
 * @Description:websocket服务相关类
 * @Date:2019-05-31
 */
@Component
@ServerEndpoint("/websocket/{sid}/{rid}")
public class WebSocketServer {

	//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

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

    //接收sid
    private String sid="";

    public static final String event = "fk_centerid";//在线单位集合key

    /**
     * @Author: wlj
     * @Description:连接建立成功调用的方法
     * @Date:2019-05-31
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid,@PathParam("rid") String rid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        this.sid=sid;
    }

    /**
     * @Author: wlj
     * @Description:连接关闭调用的方法
     * @Date:2019-05-31
     */
    @OnClose
    public void onClose(@PathParam("rid") String rid) {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
    }

    /**
     * @Author: wlj
     * @Description:收到客户端消息后调用的方法
     * @Date:2019-05-31
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Author: wlj
     * @Description:出现错误时调用的方法
     * @Date:2019-05-31
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
    
    /**
     * @Author: wlj
     * @Description:服务端推送消息方法
     * @Date:2019-05-31
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * @Author: wlj
     * @Description:群发自定义消息
     * @Date:2019-05-31
     */
    public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            try {
            	//这里可以设定只推送给这个sid的,为null则全部推送
            	if(sid==null) {
            		item.sendMessage(message);
            	}else if(item.sid.equals(sid)){
            		item.sendMessage(message);
            	}
            } catch (IOException e) {
                continue;
            }
        }
    }

    /**
     * @Author: wlj
     * @Description:获得在线连接数
     * @Date:2019-05-31
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * @Author: wlj
     * @Description:增加在线连接数
     * @Date:2019-05-31
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    /**
     * @Author: wlj
     * @Description:减少在线连接数
     * @Date:2019-05-31
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

基于redis配置推送

package cn.microvideo.flowac.services.util;

import cn.microvideo.flowac.services.common.util.MicrovideoCommRedisRepository;
import cn.microvideo.flowac.services.wsmsg.entity.WsMsgDto;
import cn.microvideo.flowac.services.wsmsg.entity.WsMsgModuleEnum;
import cn.microvideo.flowac.services.wsmsg.entity.WsProjGroupEnum;
import cn.microvideo.flowac.services.wsmsg.entity.WsReceiveDto;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Description: websocketUtil
 * @Author: xuwz
 * @Date: 2023/3/3 16:46
 */
@Component
public class WebSocketUtil {

    private static WebSocketUtil instance;

    @Resource
    private MicrovideoCommRedisRepository redisUtil;

    @PostConstruct
    public void init() {
        instance = this;
    }

    /**
     * @description 发送给所有用户
     * @author xuwz
     * @date 2023/3/6 16:16
     */
    public static void sendToAll(WsProjGroupEnum projGroupEnum, WsMsgModuleEnum wsMsgModule, Object content) {

        WsMsgDto msgDto = new WsMsgDto();
        msgDto.setWsMsgModuleEnum(wsMsgModule);
        msgDto.setContext(content);

        WsReceiveDto receiveDto = new WsReceiveDto();
        receiveDto.setReceiveBodyType(0);
        receiveDto.setMsg(msgDto);

        instance.redisUtil.strLeftPush(projGroupEnum.getProjGroup(), receiveDto, TimeUnit.MINUTES.toMillis(5));
    }

    /**
     * @description 发送给指定单位
     * @author xuwz
     * @date 2023/3/6 16:16
     */
    public static void sendToDept(WsProjGroupEnum projGroupEnum, WsMsgModuleEnum wsMsgModule, String deptId,
                                  Object content) {

        WsMsgDto msgDto = new WsMsgDto();
        msgDto.setWsMsgModuleEnum(wsMsgModule);
        msgDto.setContext(content);

        WsReceiveDto receiveDto = new WsReceiveDto();
        receiveDto.setReceiveBodyType(1);
        receiveDto.setReceiveBodyCode(deptId);
        receiveDto.setMsg(msgDto);

        instance.redisUtil.strLeftPush(projGroupEnum.getProjGroup(), receiveDto, TimeUnit.MINUTES.toMillis(5));
    }

    /**
     * @description 发送给指定用户
     * @author xuwz
     * @date 2023/3/6 16:16
     */
    public static void sendToUser(WsProjGroupEnum projGroupEnum, WsMsgModuleEnum wsMsgModule, String userId,
                                  Object content) {

        WsMsgDto msgDto = new WsMsgDto();
        msgDto.setWsMsgModuleEnum(wsMsgModule);
        msgDto.setContext(content);

        WsReceiveDto receiveDto = new WsReceiveDto();
        receiveDto.setReceiveBodyType(2);
        receiveDto.setReceiveBodyCode(userId);
        receiveDto.setMsg(msgDto);

        instance.redisUtil.strLeftPush(projGroupEnum.getProjGroup(), receiveDto, TimeUnit.MINUTES.toMillis(5));
    }
}

package cn.microvideo.flowac.equipment.websocket;

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

/**
 * @Description: websocketConfig
 * @Author: xuwz
 * @Date: 2023/3/3 16:37
 */
@Configuration
public class WebSocketConfig {

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

package cn.microvideo.flowac.equipment.websocket;

import cn.microvideo.flowac.services.common.util.MicrovideoCommRedisRepository;
import cn.microvideo.flowac.services.wsmsg.entity.WsMsgDto;
import cn.microvideo.flowac.services.wsmsg.entity.WsProjGroupEnum;
import cn.microvideo.flowac.services.wsmsg.entity.WsReceiveDto;
import cn.microvideo.framework.core.util.json.MicrovideoJsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Description: ws消息发送handle
 * @Author: xuwz
 * @Date: 2023/3/14 13:53
 */
@Slf4j
@Component
public class WebSocketSendHandle {

    @Resource
    private MicrovideoCommRedisRepository redisUtil;

    /**
     * @description 初始化
     * @author xuwz
     * @date 2023/3/14 13:54
     */
    @PostConstruct
    public void init() {

        try {
            new Thread(new WebSocketSendHandleC()).start();
        } catch (Exception e) {
            log.error("", e);
        }
    }

    private class WebSocketSendHandleC implements Runnable {

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {

            log.info("【WebSocketSendHandle】已初始化完成...");

            while (true) {
                try {
                    Thread.sleep(50);
                    String msgStr = redisUtil.strRigthPop(WsProjGroupEnum.WS_EQUIP_PROJ_GROUP.getProjGroup());
                    if (StringUtils.isEmpty(msgStr)) {
                        continue;
                    }

                    WsReceiveDto wsReceiveDto = MicrovideoJsonUtil.parseObject(msgStr, WsReceiveDto.class);
                    WsMsgDto wsMsgDto = wsReceiveDto.getMsg();
                    String wsMsgStr = MicrovideoJsonUtil.toJSONString(wsMsgDto);
                    Integer receiveBodyType = wsReceiveDto.getReceiveBodyType();
                    String receiveBodyCode = wsReceiveDto.getReceiveBodyCode();

                    if (receiveBodyType == 0) {
                        WebSocketServer.sendMessageToAll(wsMsgStr);
                    } else if (receiveBodyType == 1 && !StringUtils.isEmpty(receiveBodyCode)) {
                        WebSocketServer.sendMessageToDept(wsMsgStr, receiveBodyCode);
                    } else if (receiveBodyType == 2 && !StringUtils.isEmpty(receiveBodyCode)) {
                        WebSocketServer.sendMessageToUser(wsMsgStr, receiveBodyCode);
                    }
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
    }
}

package cn.microvideo.flowac.equipment.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Description: websoceketServer
 * @Author: xuwz
 * @Date: 2023/3/3 16:40
 */
@Component
@ServerEndpoint("/websocket/{deptId}/{userId}")
@Slf4j
public class WebSocketServer {

    private static final CopyOnWriteArraySet<WebSocketServer> WS_CONN_SET = new CopyOnWriteArraySet<>();
    private Session session;
    private String userId = "";
    private String deptId = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("deptId") String deptId, @PathParam("userId") String userId) {
        this.session = session;
        this.deptId = deptId;
        this.userId = userId;
        WS_CONN_SET.add(this);
        log.info(">>>WEBSOCKET<<< userId={},sessionId={}, open connection", userId, session.getId());
    }

    @OnClose
    public void onClose() {
        log.info(">>>WEBSOCKET<<< userId={},sessionId={}, close connection", userId, session.getId());
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        log.info(">>>WEBSOCKET<<< get userId={} sessionId={} message, context={}", userId, session.getId(), message);
        return "receive message success!!";
    }

    public static void sendMessageToAll(String message) {

        log.info("【WS_SEND TO ALL】content={}", message);
        for (WebSocketServer server : WS_CONN_SET) {
            try {
                server.sendMessage(message);
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    public static void sendMessageToDept(String message, String deptId) {

        log.info("【WS_SEND TO DRPT】deptId={},content={}", deptId, message);
        for (WebSocketServer server : WS_CONN_SET) {
            try {
                if (!server.deptId.equals(deptId)) {
                    continue;
                }
                server.sendMessage(message);
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    public static void sendMessageToUser(String message, String userId) {

        log.info("【WS_SEND TO USER】userId={},content={}", userId, message);
        for (WebSocketServer server : WS_CONN_SET) {
            try {
                if (!server.userId.equals(userId)) {
                    continue;
                }
                server.sendMessage(message);
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    public void sendMessage(String message) throws IOException {
        if (session.isOpen()) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {

        log.error(">>>WEBSOCKET<<< userId={},sessionId={}, connection error, exception={}", userId, session.getId(),
                error);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值