一、创建quarkus maven项目
(官网有教程:https://quarkus.io/guides/)
二、引入websocket依赖
<!--websocket依赖-->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-undertow-websockets</artifactId>
<version>${quarkus.platform.version}</version>
</dependency>
三、写websocket服务端代码
@ServerEndpoint("/agent/deviceStatus/{userId}")
@ApplicationScoped
public class DeviceStatusWebsocket {
//已建立连接的用户
private static final Map<String, Session> users = new ConcurrentHashMap<>();
private static final Map<String, SocketUser> userMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
//String username = (String) session.getUserProperties().get(userId);后期用户登录后用户信息会存储到缓存
String username = "系统管理员";
users.put(userId, session);
SocketUser user = new SocketUser(session.getId(),username);
userMap.put(session.getId(), user);
Log.info("用户 " + userId + " 已与服务器建立连接");
}
@OnClose
public void onClose(Session session, @PathParam("userId") String userId) {
String username = "系统管理员";
Log.info("用户 " + userId + " Connection closed");
users.remove(session.getId());
userMap.remove(session.getId());
}
@OnError
public void onError(Session session, @PathParam("userId") String userId, Throwable throwable) {
Log.error("connection error:{}", throwable);
}
@OnMessage
public void onMessage(String message, @PathParam("userId") String userId) {
Log.infof("收到用户 " + userId + "的消息,消息详情{%s}:", message);
sendMsgToAllUser(Result.success("操作成功!", JSONUtil.toJsonStr(message)));//测试回应
}
/**
* @return void
* @Author Mxf
* @Date 2022/3/17 14:36
* @Description 给所有用户发送消息
* @Param [msg] 消息内容
**/
public void sendMsgToAllUser(Result msg) {
String message = JSONUtil.toJsonStr(msg);
users.values().forEach(s -> {
if (s.isOpen()) {
s.getAsyncRemote().sendObject(message, result -> {
if (result.getException() != null) {
Log.error("Unable to send message: " + result.getException());
}
});
}
});
}
/**
* @return void
* @Author Mxf
* @Date 2022/3/17 14:38
* @Description 给某个用户发送消息
* @Param [userId, msg] 接收用户的WebSocketSession ID,消息实体
**/
public void sendMsgToUser(String userId, Result msg) {
String text = JSONUtil.toJsonStr(msg);
for (String sessionId : users.keySet()) {
if (sessionId.equals(userId)) {
if (users.get(userId).isOpen()) {
users.get(userId).getAsyncRemote().sendObject(text, result -> {
if (result.getException() != null) {
Log.error("Unable to send message: " + result.getException());
}
});
}
break;
}
}
}
}
四、配置文件中配置传输大小限制和线程阻塞
quarkus:
# websocket配置传输大小和线程阻塞
websocket:
# 传输大小
max-frame-size: 5242800
# 线程阻塞默认false表示阻塞
dispatch-to-worker: true
注意:
@OnMessage(maxMessageSize = 1024*1024)已测试这个注解配置了不会改变websocket传输大小限制
五、连接测试
前端页面websocket客户端地址:http://www.websocket-test.com/