Spring 4 WebSocket发送到指定用户:convertAndSendToUser函数

来源:互联网 发布:键盘反应速度调节软件 编辑:程序博客网 时间:2024/06/13 01:41

有时推送需要推送到指定的用户,这时就需要使用@SengToUser注解或者convertAndSendToUser这个函数,需要注意的是,推送到特定用户不一定非要使用Spring Security这个框架来实现登录和访问控制,我在项目中使用的是Apache Shiro。
在用户登录之后,在Session里面设置相应的Principal:

        UsernamePasswordToken token = new UsernamePasswordToken(phonenum, password);        token.setRememberMe(true);        currentUser.login(token);        Session session = currentUser.getSession();        session.setAttribute("user_id", user_id);        session.setAttribute("phonenum", phonenum);

然后就可以发送给指定用户了:

    public void handleMessage(Baobiaoorder order) {        log.info("收到来自RabbitMQ的消息:" + order.getOuttradeno());//        operations.convertAndSend("/topic/pay-result", order);        operations.convertAndSendToUser(order.getPhonenum(), "/queue/pay-result", order);    }

其中order.getPhonenum()便是Session里面的手机号,因为我是把手机号作为Shiro的Principal。此时消息会发送给/queue/pay-result这个目的地,但是客户端需要订阅的是/user/queue/pay-result。值得注意的是,按照惯例,最好把这种发送给特定用户的、非广播式的目的地设置为queue而不是topic。这样就能做到发送消息给指定的用户了。

2 2
原创粉丝点击