在Spring4中配置WebSocket服务器

在Spring4中配置WebSocket服务器,spring,websocket,message-queue,sockjs,spring-websocket,Spring,Websocket,Message Queue,Sockjs,Spring Websocket,我正在使用Spring4通过WebSocket开发一个实时通知系统 源代码如下: WebSocketConfig: @Configuration @EnableScheduling @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpo

我正在使用Spring4通过WebSocket开发一个实时通知系统

源代码如下:

WebSocketConfig:

@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/lrt").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/queue/", "/topic/");
        registry.setApplicationDestinationPrefixes("/app");
    }

}
@Service
public class LRTStatusListener implements ApplicationListener<BrokerAvailabilityEvent>{

    private static final Logger LOG = LoggerFactory.getLogger(LRTStatusListener.class);
    private final static long LRT_ID = 1234567890;
    private final static String LRT_OWNER = "Walter White";
    private final LRTStatusGenerator lrtStatusGenerator = new LRTStatusGenerator(LRT_ID, LRT_OWNER);
    private final MessageSendingOperations<String> messagingTemplate;
    private AtomicBoolean brokerAvailable = new AtomicBoolean();

    @Autowired
    public LRTStatusListener(MessageSendingOperations<String> messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @Override
    public void onApplicationEvent(BrokerAvailabilityEvent event) {
        this.brokerAvailable.set(event.isBrokerAvailable());
    }

    @Scheduled(fixedDelay=2000)
    public void sendLRTStatus() {
        LRTStatus lrtStatus = this.lrtStatusGenerator.generateLRTStatus();
        if (LOG.isTraceEnabled())
            LOG.trace("Sending LRT status");
        if (this.brokerAvailable.get())
            this.messagingTemplate
                .convertAndSend("/topic/status" + lrtStatus.getLRTId(), lrtStatus);
    }

    // Random status generator
    private static class LRTStatusGenerator {

        private LRTStatus lrtStatus;

        public LRTStatusGenerator(long lrtId, String owner) {
            lrtStatus = new LRTStatus(lrtId, owner, getCurrentTimestamp(), generateLRTStatusMessage());
        }

        public LRTStatus generateLRTStatus() {
            lrtStatus.setMessage(generateLRTStatusMessage());
            return lrtStatus;
        }

        private String getCurrentTimestamp() {
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            return timestamp.toString();
        }

        private String generateLRTStatusMessage() {
            String statusMessage;
            switch ((int) Math.random() * 2) {
            case 1:
                statusMessage =
                        "HANK: What? You want me to beg? You're the smartest guy I ever met. " +
                        "And you're too stupid to see... he made up his mind ten minutes ago.";
                break;
            case 2:
                statusMessage =
                        "WALTER: That's right. Now say my name. " +
                        "- DECLAN: ...You're Heisenberg. - WALTER: You're goddamn right.";
                break;
            default:
                statusMessage =
                        "WALTER: I am not in danger, Skyler. I am the danger! " +
                        "A guy opens his door and gets shot and you think that of me? " +
                        "No. I am the one who knocks!";
                break;
            }
            return statusMessage;
        }

    }

}
LRTStatusListener:

@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/lrt").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/queue/", "/topic/");
        registry.setApplicationDestinationPrefixes("/app");
    }

}
@Service
public class LRTStatusListener implements ApplicationListener<BrokerAvailabilityEvent>{

    private static final Logger LOG = LoggerFactory.getLogger(LRTStatusListener.class);
    private final static long LRT_ID = 1234567890;
    private final static String LRT_OWNER = "Walter White";
    private final LRTStatusGenerator lrtStatusGenerator = new LRTStatusGenerator(LRT_ID, LRT_OWNER);
    private final MessageSendingOperations<String> messagingTemplate;
    private AtomicBoolean brokerAvailable = new AtomicBoolean();

    @Autowired
    public LRTStatusListener(MessageSendingOperations<String> messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @Override
    public void onApplicationEvent(BrokerAvailabilityEvent event) {
        this.brokerAvailable.set(event.isBrokerAvailable());
    }

    @Scheduled(fixedDelay=2000)
    public void sendLRTStatus() {
        LRTStatus lrtStatus = this.lrtStatusGenerator.generateLRTStatus();
        if (LOG.isTraceEnabled())
            LOG.trace("Sending LRT status");
        if (this.brokerAvailable.get())
            this.messagingTemplate
                .convertAndSend("/topic/status" + lrtStatus.getLRTId(), lrtStatus);
    }

    // Random status generator
    private static class LRTStatusGenerator {

        private LRTStatus lrtStatus;

        public LRTStatusGenerator(long lrtId, String owner) {
            lrtStatus = new LRTStatus(lrtId, owner, getCurrentTimestamp(), generateLRTStatusMessage());
        }

        public LRTStatus generateLRTStatus() {
            lrtStatus.setMessage(generateLRTStatusMessage());
            return lrtStatus;
        }

        private String getCurrentTimestamp() {
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            return timestamp.toString();
        }

        private String generateLRTStatusMessage() {
            String statusMessage;
            switch ((int) Math.random() * 2) {
            case 1:
                statusMessage =
                        "HANK: What? You want me to beg? You're the smartest guy I ever met. " +
                        "And you're too stupid to see... he made up his mind ten minutes ago.";
                break;
            case 2:
                statusMessage =
                        "WALTER: That's right. Now say my name. " +
                        "- DECLAN: ...You're Heisenberg. - WALTER: You're goddamn right.";
                break;
            default:
                statusMessage =
                        "WALTER: I am not in danger, Skyler. I am the danger! " +
                        "A guy opens his door and gets shot and you think that of me? " +
                        "No. I am the one who knocks!";
                break;
            }
            return statusMessage;
        }

    }

}
应用程序通过每2000ms更改一次信息来模拟长时间运行事务(LRT)的状态

现在,我通过SockJS定义一个客户端来测试WebSocket:

<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script>
    var sock = new SockJS('/lrt');
    sock.onopen = function() {
        console.log('open');
    };
    sock.onmessage = function(e) {
        console.log('message', e.data);
    };
    sock.onclose = function() {
        console.log('close');
    };
</script>

var sock=new SockJS('/lrt');
sock.onopen=函数(){
console.log('open');
};
sock.onmessage=函数(e){
console.log('消息',例如数据);
};
sock.onclose=函数(){
console.log('close');
};
连接正常,但我看不到数据流

如何正确配置应用程序,以便生成WebSocket服务器发送的消息,然后在客户端控制台上进行路由


请注意,我还使用内置的消息代理来管理消息队列。

这是您当前仅有的JavaScript代码吗?:

<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script>
    var sock = new SockJS('/lrt');
    sock.onopen = function() {
        console.log('open');
    };
    sock.onmessage = function(e) {
        console.log('message', e.data);
    };
    sock.onclose = function() {
        console.log('close');
    };
</script>
您需要创建一个JavaScript STOMP客户端(通过SockJS)来订阅这些内容,例如:

stompClient.subscribe("/topic/status*", function(message) {
    ...
});

stompClient.subscribe("/queue/whatever", function(message) {
    ...
});

查看应用程序以获得完整的工作示例。

@vdenotaris:乍一看,它看起来还可以