前面说到,使用websocket通讯,现在说说应用上的通讯,stomp - streaming / simple text oriented protocol. 流/简单 文本协议。应用方面,一般采用该种协议,是websocket协议的一个子协议,了解一下既可。
stomp协议,配置时注意一个地方,stomp协议使用的中继器(路由)或者叫消息中介,默认在configureMessageBroker方法中,registry.enableSimpleBroker是使用内存中介,不依赖第三方组件,registry.enableStompBrokerRelay是使用第三方中间件,需要事先下载安装中间件,如activeMQ/RabbitMQ.本例子中使用内存中继。
具体代码实现:
1. WebSocketMessageBrokerConfigurer配置类,继承AbstractWebSocketMessageBrokerConfigurer重写下面方法。
package com.websocket.stomp;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
/**
* stomp websocket的子协议,stomp: simple/streaming text oriented message protocol. 简单/流 文本消息协议,
* 选择使用内存中级,还是使用activeMQ等中间件服务器
* @author tomZ
* @date 2016年11月3日
* @desc TODO
*/
@Configuration
@EnableWebSocketMessageBroker
public class MyWebSocketMessageBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {
/**
* 连接的端点,客户端建立连接时需要连接这里配置的端点
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//为java stomp client提供链接
registry.addEndpoint("/client")
.setAllowedOrigins("*")
.setHandshakeHandler(new MyHandshakeHandler())
.addInterceptors(new MyHandshakeInterceptor());
//为js客户端提供链接
registry.addEndpoint("/hello")
.setAllowedOrigins("*")
.setHandshakeHandler(new MyHandshakeHandler())
.addInterceptors(new MyHandshakeInterceptor())
.withSockJS();
}
/**
* applicationDestinationPrefixes应用前缀,所有请求的消息将会路由到@MessageMapping的controller上,
* enableStompBrokerRelay是代理前缀,而返回的消息将会路由到代理上,所有订阅该代理的将收到响应的消息。
*
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/