微信小程序+springboot及时聊天(通讯)代码
立即下载
资源介绍:
1.微信小程序ws通讯
2.后端使用springboot的websocket
package com.example.mengchuangyuan.common.chat.mini.mapper;
import com.alibaba.fastjson.JSON;
import com.example.mengchuangyuan.common.redis.mapper.RedisUtils;
import com.example.mengchuangyuan.common.redis.tool.SufferVariable;
import com.example.mengchuangyuan.common.tool.DateYMDms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import javax.websocket.Session;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Component
@Slf4j
public class SessionPool {
@Autowired
private RedisUtils redisUtils;
//key-value : userId - 会话(系统创建)
public static Map sessions = new ConcurrentHashMap<>();//避免多线程问题
public void close(String sessionId) {
//sessionId是在session中添加了一个标识,准确定位某条session
for (String userId : SessionPool.sessions.keySet()) {
Session session = SessionPool.sessions.get(userId);
if (session.getId().equals(sessionId)) {
sessions.remove(userId);
break;
}
}
}
public void sendMessage(String userId, String message) {
sessions.get(userId).getAsyncRemote().sendText(message);
}
//消息的群发,业务逻辑的群发
public void sendMessage(String message) {
// redisUtils.cacheValue("chatMessage","String.valueOf(SufferVariable.messageMap)");
for (String sessionId : SessionPool.sessions.keySet()) {
SessionPool.sessions.get(sessionId).getAsyncRemote().sendText(message);
}
}
//点对点的消息推送
public void sendMessage(Map params) {
log.info("消息内容:"+String.valueOf(params));
long mid = System.currentTimeMillis();
Map formUser = (Map) params.get("formUser");
Map toUser = (Map) params.get("toUser");
String userId = formUser.get("openid").toString();
String toUserId = toUser.get("openid").toString();
// String msg = params.get("message").toString();
String type = params.get("type").toString();
String linkType = params.get("linkType").toString();
//获取用户session
Session session = sessions.get(toUserId);
Map keyMap;
List setOpenid;
Map map;
List