springboot项目中先是集成了websocket,后面我又集成了webflux,然后我发现webflux和websocket会冲突,webflux会使用不了,如何能使两者同时可以互不干扰呢。
在springcloud项目中,gateway也是使用了webflux,然后新建服务使用websocket也会偶现错误,分析不出来原因,不知道是不是两者冲突导致的。求解。
参考GPT和自己的思路:对于第一个问题,可以尝试在集成webflux时设置合适的路由规则来避免与websocket的路由冲突。具体做法可以参考springboot官方文档中对路由规则的介绍以及相关示例。
至于第二个问题,可能存在的冲突源可能比较复杂,可能涉及多个层面和组件之间的互相影响,需要详细排查才能得知具体原因。一般来说,可以先检查配置文件和路由规则是否正确,然后查看相关日志信息来确定具体的错误原因,并结合具体代码进行排查和调试。
package com.gjx.server.webserver.server;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author gjx
* @email 13450753745@163.com
* @description websocket的服务端类
* @Date 2019/10/14
*/
@ServerEndpoint("/serverTest")
@RestController
public class WebSocketServer {
/**
*存放所有的在线客户端
* */
private static Map<String, Session> clients = new ConcurrentHashMap<>();
/**
* 客户端与服务端连接时触发执行事件
*/
@OnOpen
public void onOpen(Session session) throws InterruptedException, IOException {
System.out.println("有新的客户端连接进来了");
clients.put(session.getId(), session);
}
/**
* 向客户端发送字符串信息
*/
private static void sendMsg(Session session, String msg) throws IOException {
session.getBasicRemote().sendText(msg);
}
/**
*接收到消息后的处理方式,其中包含客户端的普通信息和心跳包信息,
* 简单区别处理
*/
@OnMessage
public void onMessage(Session session, String msg) throws Exception {
if (!msg.equals("keepalive")){
System.out.println("服务端收到消息:" + msg);
Thread.sleep(3000L);
sendMsg(session,msg);
}else{
System.out.println("心跳维护包:" + msg);
}
}
@OnClose
public void onClose(Session session) {
System.out.println("有客户端断开连接了,断开客户为:" + session.getId());
clients.remove(session.getId());
}
@OnError
public void onError(Throwable throwable) {
System.out.println("服务端出现错误");
throwable.printStackTrace();
}
}