SpringBoot+WebSocket 实现订单提示功能

Java+WebSocket 实现订单提示功能

  • 首先socket API 定义好
    • SpringBoot启动类 添加开启 WebSocket
    • 开放权限 (具体更具自己 项目)
    • 找到订单的借口调用API 确保有了订单在加上下面这个代码
    • Web 前端代码

首先socket API 定义好


package com.recruit.work.controller.socket;

import com.alibaba.fastjson.JSONObject;

import com.recruit.work.bean.AppMsg;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
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.ConcurrentHashMap;

/**
 * @author 老肖
 * @packge com.xbxkj.config.config
 * @data 2019-06-11 12:00
 * @project Metaphysics
 */
@ServerEndpoint(value = "/websocket/{userId}/{type}" )
@Component
public class MyWebSocket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap webSocketSet = new ConcurrentHashMap();

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



    //此处是解决无法注入的关键
    private static ApplicationContext applicationContext;
    //要注入的service或者dao
    public static void setApplicationContext(ApplicationContext applicationContext) {
        MyWebSocket.applicationContext = applicationContext;
    }

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(@PathParam(value = "userId") String param, @PathParam(value = "type") String type, Session session) {
        this.session = session;
        webSocketSet.put(param,this);     //加入set中
        thisType=type;
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());

    }

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

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {

        JSONObject jo = new JSONObject();

        jo.put("message", message);


        System.out.println("来自客户端的消息:" + jo.toString());



        AppMsg appMsg=  JSONObject.parseObject(jo.toString(), AppMsg.class);

        sendInfo(jo.toString());

    }

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


    public void sendMessage(String message) throws IOException {
        try {
            this.session.getBasicRemote().sendText(message);
            System.out.println("发送出了新消息了");


        }catch (Exception e){
            webSocketSet.remove(this);  //从set中删除
        }

        //this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (String key : webSocketSet.keySet()) {
            try {
                String type=webSocketSet.get(key).thisType;
                //如果 循环到后台 那么发送提醒
                if(type.equals("admin")){


                    JSONObject jo = new JSONObject();

                    jo.put("message", message);

                    System.out.println("有人注册了");

                    webSocketSet.get(key).sendMessage(jo.toString());
                }

            } catch (IOException e) {
                continue;
            }
        }
    }

    /**
     * 单发自定义消息
     * userId 给谁发
     * */
    public static void sendToUser(String message,String userId) throws IOException {
        for (String key : webSocketSet.keySet()) {
            if(key.equals(userId)){
                try {
                    webSocketSet.get(key).sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}

SpringBoot启动类 添加开启 WebSocket

  //springboot2.0开启websocket支持
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        log.info("正在启动开启websocket支持") ;
        return new ServerEndpointExporter();
    }

开放权限 (具体更具自己 项目)

  map.put("/websocket/**", "anon");

找到订单的借口调用API 确保有了订单在加上下面这个代码

    try {

				//通知所有人的方法
                MyWebSocket.sendInfo("0");

                System.out.println("有新的用户 ");

            } catch (IOException e) {
                e.printStackTrace();
            }

Web 前端代码

//这个是标签    



如果这个代码对你有帮助 请对我有点点 小小的支持 让我更新下去!

你可能感兴趣的:(java,websocket,js)