When I create a connection via websocket, I want to find the user's information from the database and store it in "friendsList" but when I call "getUserByUid" via "userMapper", it gives me null. enter image description here "CKt3z2RW6s" is uid.
I tried to put "userMapper.getUserByUid()" in another method, and receive it through the User object. This is my code
package com.chat.imbackend.controller;
import com.alibaba.fastjson.JSON;
import com.chat.imbackend.entity.Friends;
import com.chat.imbackend.entity.Messages;
import com.chat.imbackend.entity.User;
import com.chat.imbackend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
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.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
@CrossOrigin
@RestController
@ServerEndpoint(value = "/websocket/{uid}")
public class WebSocketController {
private Session session;
@Autowired
private UserMapper userMapper;
/**
* 好友列表
*/
public static List<Friends> friendsList = new ArrayList<>();
/**
* 定义并发HashMap存储好友WebSocket集合
*/
public static ConcurrentHashMap<String, WebSocketController> webSocketSession = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(@PathParam(value = "uid") String uid, Session session) {
// 设置session
this.session = session;
// Put添加当前类
webSocketSession.put(uid, this);
try {
System.out.println(uid);
User user = userMapper.getUserByUid(uid);
// Add添加当前好友信息
friendsList.add(Friends.builder().uid(uid).nickname(user.getNickname()).avatar(user.getAvatar()).build());
// 通知更新好友信息列表
updateFriendInformationList();
log.info("【WebSocket消息】有新的连接[{}], 连接总数:{}", uid, webSocketSession.size());
}catch(Exception e){
log.error(e.getMessage());
}
}
/**
* 通知更新好友信息列表
*/
private synchronized void updateFriendInformationList() {
webSocketSession.forEach((key, val) -> {
// 初始化存储属于自己的好友列表 排除自己
List<Friends> friends = new ArrayList<>();
// 迭代所有好友列表
friendsList.forEach((friend) -> {
// 在 所有好友信息列表 中验证非自己
if (!friend.getUid().equals(key)) {
// 追加非自己的好友信息
friends.add(friend);
}
});
// 发送消息
sendP2PMessage(key, JSON.toJSONString(Messages.builder().type("updateFriendsList").receiveUid(key).messages(friends).build()));
});
}
@OnMessage
public void onMessage(@PathParam(value = "uid") String uid, String message) {
log.info("【WebSocket消息】 收到客户端[{}] 发送消息:{} 连接总数:{}", uid, message, webSocketSession.size());
// 验证消息内容
if (StringUtils.hasLength(message)) {
try {
// 消息内容转消息对象
Messages messages = JSON.parseObject(message, Messages.class);
// 发送消息
sendP2PMessage(messages.getReceiveUid(), message);
} catch (Exception e) {
log.error("WebSocket消息异常:", e);
}
}
}
@OnClose
public void onClose(@PathParam(value = "uid") String uid) {
friendsList.remove(friendsList.stream().filter((friends -> friends.getUid().equals(uid))).findAny().orElse(null));
webSocketSession.remove(uid);
// 通知更新好友信息列表
updateFriendInformationList();
log.info("【WebSocket消息】客户端[{}]连接断开, 剩余连接总数:{}", uid, webSocketSession.size());
}
/**
* 点对点发送
*/
public static synchronized void sendP2PMessage(String uid, String message) {
log.info("【WebSocket消息】点对点发送消息, uid={} , message={}", uid, message);
try {
webSocketSession.get(uid).session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("点对点发送异常:", e);
}
}
}
package com.chat.imbackend.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.util.Date;
@Data
@TableName("tbl_users")
public class User {
@TableId(type = IdType.AUTO)
Integer id;
String uid;
String nickname;
String password;
String avatar = "src/assets/Resource/avatar/defaultAvatar.png";
@TableField(fill = FieldFill.INSERT)
Date jtime;
}
package com.chat.imbackend.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.chat.imbackend.entity.User;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("select * from tbl_users where uid= #{uid}")
User getUserByUid(@Param("uid") String uid);
@Update("UPDATE tbl_users SET nickname = #{nickname} WHERE uid = #{uid}")
void modifyUser(@Param("uid") String uid, @Param("nickname") String nickname);
@Update("UPDATE tbl_users SET avatar = #{avatar} WHERE uid = #{uid}")
void modifyAvatar(@Param("uid") String uid, @Param("avatar") String avatar);
}
I found this. My userMapper in this class is null. Why?