在实现自己需要WebSocket的过程里,遇见了种种问题,再此总结一下。

问题

javax.websocket.EncodeException: No encoder specified for object of class [类型](类型问题)Cannot invoke “com.example.yungongju.impl.async.RealTimeServiceImpl.list()” because “com.example.yungongju.config.WebSocketServer.realTimeService” is null(mapper无法注入)caught TypeError: Cannot set properties of undefined (setting ‘data’)(this无法使用)

解决

Cannot invoke “com.example.yungongju.impl.async.RealTimeServiceImpl.list()” because “com.example.yungongju.config.WebSocketServer.realTimeService” is null

这个问题讲述的无法注入mapper的问题,导致我们也没有办法使用mybatis。 如果用的是mybatis-plus,我们最好使用3.5.3版本,低版本会有冲突。 本质原因:spring管理的都是单例(singleton),和 websocket (多对象)相冲突。 解决办法很简单,这样写

private static RealTimeMapper realTimeMapper;

@Resource

public void setRealTimeMapper(RealTimeMapper realTimeMapper) {

WebSocketServer.realTimeMapper = realTimeMapper;

}

private static DataInformationServiceImpl dataInformationService;

@Resource

public void setDataInformationService(DataInformationServiceImpl dataInformationService) {

WebSocketServer.dataInformationService = dataInformationService;

}

javax.websocket.EncodeException: No encoder specified for object of class [类型](类型问题)

修改注解

@ServerEndpoint(value = "/imserver/{userId}", encoders = {ServerEncoder.class})

@Component

public class WebSocketServer {

然后ServerEncoder工具类就OK了。

package com.example.yungongju.config;

import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import javax.websocket.EncodeException;

import javax.websocket.Encoder;

import javax.websocket.EndpointConfig;

import java.util.HashMap;

/**

* @desc: WebSocket编码器

* @author: ysdysyn

* @since: 2023-12-27

*/

public class ServerEncoder implements Encoder.Text {

private static final Logger log = LoggerFactory.getLogger(ServerEncoder.class);

/**

* 这里的参数 hashMap 要和 Encoder.Text保持一致

* @param hashMap

* @return

* @throws EncodeException

*/

@Override

public String encode(HashMap hashMap) throws EncodeException {

/*

* 这里是重点,只需要返回Object序列化后的json字符串就行

* 你也可以使用gosn,fastJson来序列化。

* 这里我使用fastjson

*/

try {

return JSONObject.toJSONString(hashMap);

}catch (Exception e){

log.error("",e);

}

return null;

}

@Override

public void init(EndpointConfig endpointConfig) {

//可忽略

}

@Override

public void destroy() {

//可忽略

}

}

参考小刘爱搬砖

caught TypeError: Cannot set properties of undefined (setting ‘data’)

暂存this。let that = this; 在内部用that.xx代替this.xx 在出现问题的方法块里最上面写上

let that = this

到此分享完毕,请多多反馈,有问题留言哦。

小白路漫漫,让我们一起加油!!!

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: