带有RabbitMQ的SpringBoot WebSocket向特定客户端发送消息

时间:2019-02-22 09:38:44

标签: spring-boot rabbitmq amqp spring-websocket

我正在使用springboot-websocket作为聊天功能。我使用rabbitmq作为经纪人。我无法将邮件发送给特定用户。

据我了解,通过浏览许多博客和教程,我们可以使用template.convertAndSendToUser(...)方法将消息发送给特定用户。

但是该方法采用的第一个参数是String用户名。这个用户名是什么?

public class CustomSubProtocolWebSocketHandler extends SubProtocolWebSocketHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomSubProtocolWebSocketHandler.class);

    @Autowired
    private UserCommons userCommons;

    CustomSubProtocolWebSocketHandler( MessageChannel clientInboundChannel, SubscribableChannel clientOutboundChannel )
    {
        super(clientInboundChannel, clientOutboundChannel);
    }

    @Override
    public void afterConnectionEstablished( WebSocketSession session ) throws Exception
    {
        LOGGER.info(
                "************************************************************************************************************************New webSocket connection was established: {}",
                session);
        String token = session.getUri().getQuery().replace("token=", "");
        String user = Jwts.parser().setSigningKey(TokenConstant.SECRET)
                .parseClaimsJws(token.replace(TokenConstant.TOKEN_PREFIX, "")).getBody().getSubject();
        Optional<UserModel> userModelOptional = userCommons.getUserByEmail(user);
        if( !userModelOptional.isPresent() )
        {
            LOGGER.error(
                    "************************************************************************************************************************Invalid token is passed with web socket request");
            throw new DataException(GeneralConstants.EXCEPTION, "Invalid user", HttpStatus.BAD_REQUEST);
        }
        super.afterConnectionEstablished(session);
    }

    @Override
    public void afterConnectionClosed( WebSocketSession session, CloseStatus closeStatus ) throws Exception
    {
        LOGGER.error(
                "************************************************************************************************************************webSocket connection was closed");
        LOGGER.error(closeStatus.getReason());
        super.afterConnectionClosed(session, closeStatus);
    }

    @Override
    public void handleTransportError( WebSocketSession session, Throwable exception ) throws Exception
    {

        LOGGER.error(
                "************************************************************************************************************************Connection closed unexpectedly");
        LOGGER.error(GeneralConstants.ERROR, exception);
        super.handleTransportError(session, exception);
    }
}

在那个CustomSubProtocolWebSocketHandler中,我可以得到WebSocket-session-id。但是,如果我使用session-id作为第一个参数,则该消息不会发送给该用户。如何获得用户名?

0 个答案:

没有答案