一、参考
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());
}
}
}