RabbitMq加websocket应用

1定义websocket
        var websocket = null;//当前服务:端口号80

        var websocketUrl86=utils.websocketUrl86;
        // //判断当前浏览器是否支持WebSocket
        // if ('WebSocket' in window) {
        //     $.ajax({
        //         url: "/questionDisplayController/queryUid",
        //         dataType: "json",
        //         type: "post",
        //         async: false,
        //         success: function (res) {
        //             if (res.code === "00") {
        //                 var websocketUrl = websocketUrl86+'/'+ res.uid;
        //
        //                 websocket = new WebSocket(websocketUrl);
        //             }
        //         }
        //     })
        //     // websocket = new WebSocket(websocketUrl86+"?uid=11111112222222223333333444444444");//创建当前服务的连接
        //     // websocket = new WebSocket(websocketUrl86);//创建当前服务的连接
        // } else {
        //     alert('当前浏览器 Not support websocket')
        // }

        websocket = new WebSocket(websocketUrl86);//创建当前服务的连接
        //连接发生错误的回调方法
        websocket.onerror = function () {
            console.log("连接发生错误的回调方法");
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            console.log("连接成功建立的回调方法");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {

            var dataId =event.data;
            console.log("接收到消息的回调方法"+dataId);
            $(".layui-icon-refresh").click();
        }
        //连接关闭的回调方法
        websocket.onclose = function () {
            console.log("连接关闭的回调方法");
        }


        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }


        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();

        }
 2.创建mq队列
 import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FanoutRabbitConfig {

    /**
     * 定义队列A,服务于8086端口
     * @return
     */
    @Bean
    public Queue problemMessage() {
        return new Queue("q_fanout_problem");
    }




    /**
     * 定义交换机
     * @return
     */
    @Bean
    FanoutExchange fanoutproblemExchange() {
        return new FanoutExchange("mybootfanoutproblemExchange");
    }

    /**
     * 将队列A和交换机进行绑定
     * @return
     */
    @Bean
    Binding bindingproblemExchange() {
        return BindingBuilder.bind(problemMessage()).to(fanoutproblemExchange());
    }

}
3.mq往websocket中发消息
package com.medicine.customer_service.controller;


import org.apache.commons.collections.map.HashedMap;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@RabbitListener(queues = "q_fanout_problem")
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();



    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    /** 接收userId */
    private String userId = "";
    private static Map<String, WebSocketServer> webSocketMap = new HashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSocketSet.add(this);
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);// 加入set中
            addOnlineCount();// 在线数加1
        }
//        System.out.println(userId + "加入");
//        System.out.println("当前在线人数为:" + getOnlineCount());
       /* try {
            sendMessage("欢迎" + userId + "加入");
        } catch (IOException e) {
            System.out.println("IO异常");
        }*/
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); // 从set中删除
        subOnlineCount(); // 在线数减1
//        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
//        message = "来自"+userId+"的消息:" + message;
//        System.out.println("onMessage:"+message);
        // 群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     *
     */
    @OnError
    public void onError(Session session, Throwable error) {
//        System.out.println("发生错误");
        error.printStackTrace();
    }

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

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    /**
     * 发送自定义消息
     * 按userid发送消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
//        System.out.println("发送消息到:" + userId + ",报文:" + message);
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
//            System.out.println("用户" + userId + ",不在线!");
        }
    }

    /**
     * 获取在线客户端数量
     *
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 添加线上链接的客户端数量
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    /**
     * 客户端下载是调用将在线数量减1
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    /**
     * rabbit订阅队列中的消息(发送消息)
     *
     * @param message
     */
    @RabbitHandler
    public void process(String message) {
        onMessage(message, session);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值