springboot websocket 无法自动注入问题处理

一、参考

springboot websocket 无法自动注入问题处理

二、通过set方法注入

  • 主要代码
//静态属性
private static IChatService chatService;
//通过set注入
@Autowired
public void setChatService(IChatService chat) {
    chatService = chat;
}
  • 全部代码
package com.lihua.framework.websocket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lihua.framework.websocket.session.WsSession;
import com.lihua.project.system.chat.domain.Chat;
import com.lihua.project.system.chat.service.IChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lihua
 * @date 2022/4/8 21:57
 * 聊天websocket
 * @ServerEndpoint(value = "/test/ws") 前端通过此URI 和后端交互,建立连接
 */
@Slf4j
@ServerEndpoint(value = "/websocket/chat/{userId}/{otherSideUserId}")
@Component
public class ChatWebsocket {

    private static IChatService chatService;

    @Autowired
    public void setChatService(IChatService chat) {
        chatService = chat;
    }

    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /** 存放所有在线的客户端 */
    /*private static Map<String, Session> clients = new ConcurrentHashMap<>();*/

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId,Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        WsSession.putSession(userId, session);
        log.info("有新连接加入:userId={},当前在线人数为:{}", userId, onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId,Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        WsSession.remove(userId);
        log.info("有一连接关闭:userId={},当前在线人数为:{}", userId, onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(@PathParam("userId") String userId, @PathParam("otherSideUserId") String otherSideUserId, String message, Session session) {
        log.debug("userId={} msg={}", userId, message);
        Chat chat = JSON.parseObject(message, Chat.class);
        Session toSession = WsSession.getSession(otherSideUserId);
        if (toSession != null) {
            //给otherSideUserId发送消息
            this.sendMessage(message, toSession);
            //持久化消息 ,将消息标记为已读
            chat.setMsgState("1");
            chatService.insertChat(chat);
        }else {
            //说明对方不在线
            //TODO 这里可以弄一个邮箱提醒
            log.info("{}已离线",otherSideUserId);
            chatService.insertChat(chat);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败:{}", e.getMessage());
        }
    }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值