websoet链接后,如何在多服务环境中进行通信呢?
websocket实现
@Service
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.springboot.cloud.message.config.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.OnClose;
import javax.websocket.OnError;
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
// 这块key加不加都可以,根据公司需求来(我们是支持同一用户多地登录的,故传递的是token)
@ServerEndpoint(value = "/websocket/{id}/{key}", subprotocols = {"protocol"})
public class WebSocketServer {
private static int onlineCount = 0;
private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<>();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private String id = "";
private String key = "";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(@PathParam(value = "id") String id, @PathParam("key") String key, Session session) {
log.info("websocket连接,id:{},key:{}", id, key);
if (StringUtils.isEmpty(id) || StringUtils.isEmpty(key)) {
return;
}
if ("null".equals(id) || "null".equals(key)) {
return;
}
this.session = session;
//接收到发送消息的人员编号
this.id = id;
this.key = key;
List<String> ids = map.get(id);
if (StringUtils.isEmpty(ids)) {
ids = new ArrayList<>();
}
ids.add(key);
map.put(id, ids);
//加入set中
webSocketSet.put(key, this);
//在线数加1
addOnlineCount();
log.info("用户" + id + "连接成功!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
log.info("websocket断开,id:{},key:{}", this.id, this.key);
//删除map中值
List<String> keys = map.get(this.id);
if (!CollectionUtils.isEmpty(keys)) {
for (int i = 0; i < keys.size(); i++) {
if (this.key.equals(keys.get(i))) {
keys.remove(i);
i--;
}
}
//从set中删除
webSocketSet.remove(this.key);
//在线数减1
subOnlineCount();
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message) throws IOException {
sendMessage("ok");
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
try {
session.close();
} catch (IOException e) {
log.error(e.getMessage());
}
error.printStackTrace();
}
/**
* 服务端主动推送消息
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
synchronized (this.session) {
this.session.getBasicRemote().sendText(message);
}
}
/**
* 发送信息给指定ID用户,如果用户不在线则返回不在线信息给自己
*
* @param message
* @param personKeys
* @throws IOException
*/
public static void sendToUser(String message, List<String> personKeys) throws IOException {
log.info("发送信息开始:{},{}", message, JSON.toJSONString(personKeys));
//获取人员集合
for (String personKey : personKeys) {
//获取map中对应的链接
if (map.get(personKey) != null && !CollectionUtils.isEmpty(map.get(personKey))) {
//遍历给连接人发送信息
for (String s : map.get(personKey)) {
if (!StringUtils.isEmpty(webSocketSet.get(s))) {
webSocketSet.get(s).sendMessage(message);
}
}
} else {
//如果用户不在线则返回不在线信息给自己
log.error("当前用户不在线:" + personKey);
}
}
}
/**
* 发送信息给所有人
*
* @param
* @throws IOException
*/
public static void sendToAll(String message) throws IOException {
log.info("发送全体信息开始:{}", message);
for (String key : webSocketSet.keySet()) {
try {
if (!StringUtils.isEmpty(webSocketSet.get(key))) {
webSocketSet.get(key).sendMessage(message);
}
} catch (IOException e) {
log.info(e.getMessage());
}
}
log.info("发送全体信息结束");
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
redis订阅多服务实现
在上述代码基础上,已经可以实现websocket通信,但是同时部署了2台,3台服务,这时我们需要怎么去处理呢?
通过redis订阅,发送消息时,根据交换机去所有服务进行发送,判断当前用户是否在线,在线发送消息即可。
直接上代码
import com.springboot.cloud.message.websocket.RedisReceiver;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
@Configuration
@EnableCaching
public class RedisCacheConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
// 可以添加多个 messageListener,配置不同的交换机
// 订阅最新消息频道
container.addMessageListener(listenerAdapter, new PatternTopic("websocketPushPrivate"));
container.addMessageListener(listenerAdapter, new PatternTopic("websocketPushAll"));
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(RedisReceiver receiver) {
// 消息监听适配器
return new MessageListenerAdapter(receiver, "onMessage");
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.springboot.cloud.message.dto.Res.WebSocketVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class RedisReceiver implements MessageListener {
@Autowired
WebSocketServer webSocketServer;
/**
* 处理接收到的订阅消息
*/
@Override
public void onMessage(Message message, byte[] pattern) {
// 订阅的频道名称
String channel = new String(message.getChannel());
String msg = "";
try {
// 按照自己公司业务处理即可
if ("websocketPushPrivate".endsWith(channel) || "websocketPushAll".endsWith(channel)) {
//注意与发布消息编码一致,否则会乱码
msg = new String(message.getBody(), "UTF-8");
if (StringUtil.isNotBlank(msg)) {
WebSocketVo webSocketVo = JSONObject.parseObject(msg, WebSocketVo.class);
// 最新消息
if ("websocketPushPrivate".endsWith(channel)) {
WebSocketServer.sendToUser(webSocketVo.getMessage(), webSocketVo.getPersonKeys());
} else if ("websocketPushAll".endsWith(channel)) {
WebSocketServer.sendToAll(webSocketVo.getMessage());
} else {
}
} else {
log.info("消息内容为空,不处理。");
}
}
} catch (Exception e) {
log.error("处理消息异常:" + e.toString());
e.printStackTrace();
}
}
}
@Override
// 推送到人
public Result sendWebSocketMessage(List<String>personKeys, String message) throws IOException {
WebSocketVo webSocketVo = new WebSocketVo();
webSocketVo.setMessage(message);
webSocketVo.setPersonKeys(personKeys);
template.convertAndSend("websocketPushPrivate", JSON.toJSONString(webSocketVo));
return Result.success();
}
@Override
// 推送全部
public Result sendWebSocketMessagePo(String message) throws IOException {
WebSocketVo webSocketVo = new WebSocketVo();
webSocketVo.setMessage(message);
template.convertAndSend("websocketPushAll", JSON.toJSONString(webSocketVo));
return Result.success();
}
基本上就可以了,主要注意交换机参数,其他基本上没问题~