quarkus框架集成websocket配置传输大小限制和线程阻塞-Java

一、创建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/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值