天天看點

SpringBoot內建WebSocket實作消息推送

引入Maven依賴

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
           

配置config

建立config檔案夾,編寫WebSocketConfig類

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();
    }
}
           

編寫WebSocketService類

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

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
//@ServerEndpoint("/websocket/{user}")
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
    //靜态變量,用來記錄目前線上連接配接數。應該把它設計成線程安全的。
    private static int onlineCount = 0;
    //concurrent包的線程安全Set,用來存放每個用戶端對應的MyWebSocket對象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //與某個用戶端的連接配接會話,需要通過它來給用戶端發送資料
    private Session session;

    /**
     * 連接配接建立成功調用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //線上數加1
        log.info("有新連接配接加入!目前線上人數為" + getOnlineCount());
        try {
            sendMessage("連接配接成功");
        } catch (IOException e) {
            log.error("websocket IO異常");
        }
    }
    //	//連接配接打開時執行
    //	@OnOpen
    //	public void onOpen(@PathParam("user") String user, Session session) {
    //		currentUser = user;
    //		System.out.println("Connected ... " + session.getId());
    //	}

    /**
     * 連接配接關閉調用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中删除
        subOnlineCount();           //線上數減1
        log.info("有一連接配接關閉!目前線上人數為" + getOnlineCount());
    }

    /**
     * 收到用戶端消息後調用的方法
     *
     * @param message 用戶端發送過來的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("來自用戶端的消息:" + message);

        //群發消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("發生錯誤");
        error.printStackTrace();
    }


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


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

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

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

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

           

編寫你要發送内容的Java類,我用的是一個Controller,通路這個接口直接

發送socket消息給使用者

@RestController
@RequestMapping(value = "/socket/api/",  produces = "text/html;charset=utf-8")
public class SocketApiController {

    @Autowired
    private NjkUserMapper userMapper;
    @Autowired
    private InquiryMapper inquiryMapper;
    @Autowired
    private NjkUserServiceMapper njkUserServiceMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @PostMapping("sendToUser")
    public String sendToUser(String type, String userId, String orderNum) {

        try {
            InquiryEntity inquiryEntity = new InquiryEntity();
            inquiryEntity.setInquiryStatus(0);
            inquiryEntity.setCreateTime(new Date());
            inquiryEntity.setUserId(userId);
            inquiryEntity.setProductId(orderNum);
            inquiryMapper.insert(inquiryEntity);
            NjkUserEntity njkUserEntity = userMapper.selectByPrimaryKey(userId);
            Example example = new Example(NjkUserServiceEntity.class);
            example.createCriteria().andEqualTo("serviceId", njkUserEntity.getServiceId());
            NjkUserServiceEntity njkUserServiceEntity = njkUserServiceMapper.selectOneByExample(example);
            if (njkUserServiceEntity != null && !"".equals(njkUserServiceEntity)) {
                String message = "";
                if ("1".equals(type)) {
                    message = njkUserServiceEntity.getName() + ",請注意,客戶\'" + njkUserEntity.getNickName() + "\'送出了VIP申請資訊,請及時處理以及回饋!聯系方式:" + njkUserEntity.getPhone();
                    message = "{\"type\":\"1\",\"msg\":\"" + message + "\",\"serviceId\":\""+njkUserEntity.getServiceId()+"\"}";

                } else if ("2".equals(type)) {
                    message = njkUserServiceEntity.getName() + ",請注意,客戶\'" + njkUserEntity.getNickName() + "\'送出了咨詢資訊,請及時處理以及回饋!聯系方式:" + njkUserEntity.getPhone();
                    message = "{\"type\":\"2\",\"msg\":\"" + message + "\",\"serviceId\":\""+njkUserEntity.getServiceId()+"\"}";

                } else if ("3".equals(type)) {
                    message = njkUserServiceEntity.getName() + ",請注意,客戶\'" + njkUserEntity.getNickName() + "\'支付了訂單,請及時處理以及回饋!訂單号為:" + orderNum;
                    message = "{\"type\":\"3\",\"msg\":\"" + message + "\",\"serviceId\":\""+njkUserEntity.getServiceId()+"\"}";

                }
                webSocketServer.sendInfo(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "失敗";
        } catch (Exception e) {
            e.printStackTrace();
            return "失敗";
        }
        return "成功";
    }
           

重要的地方在這兩個地方

SpringBoot內建WebSocket實作消息推送

接下來就是測試WebSocket是否可用

我是直接上這個網址去測試的websocket線上測試

測試圖

SpringBoot內建WebSocket實作消息推送

通過前端代碼

socket = new WebSocket("ws://localhost:9997/appManager/websocket");
           

其中,appManager是工程名,/webscoket是通路路徑名

建立連接配接,前端調用scoket.open() 會使背景在靜态成員變量webSocketSet裡面增加一個元素,相當于一個緩存。背景服務調用sendMessage

(指定某個使用者,定向)或sendInfo(周遊webSocketSet逐個發送,類似群發)方法,即可向已登入的用戶端推送消息。