总结一下实现过的springboot+websocket+stomp+sockjs+rabbitmq的问题
如何实现,网上的代码非常多,很容易就实现,具体的理解要看自己了,websocket本身是支持
文本和二进制传输,但是sockJS是不支持二进制的,经过查询了一下,作者也说没有时间搞这一块,lz自己测试客户端到服务端是可以传输二进制的,但是服务器无法向web端传输二进制,发送二进制会断开websocket连接。所以如果需要传输二进制,可以直接使用websocket。sockjs的优势在于可以处理不支持websocket的浏览器,会使用轮训来实现
使用的是springboot2.1.7
pom.xml添加依赖
org.springframework.boot
spring-boot-starter-websocket
org.springframework.boot
spring-boot-starter-amqp
java类
import java.security.Principal;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.messaging.converter.ByteArrayMessageConverter;
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.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
@Configuration
@EnableWebSocketMessageBroker // 注解开启STOMP协议来传输基于代理的消息,此时控制器支持使用@MessageMapping
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/user");// topic用来广播,user用来实现p2p
}
@Override
public boolean configureMessageConverters(List messageConverters) {
messageConverters.add(new ByteArrayMessageConverter());
return true;
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/webServer").setHandshakeHandler(new DefaultHandshakeHandler() {
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
Map attributes) {
// 将客户端标识封装为Principal对象,从而让服务端能通过getName()方法找到指定客户端
Object o = attributes.get("name");
return new FastPrincipal(o.toString());
}
}).addInterceptors(new HandleShakeInterceptors()).setAllowedOrigins("*");//.withSockJS()
registry.addEndpoint("/queueServer").setHandshakeHandler(new DefaultHandshakeHandler() {
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
Map attributes) {
// 将客户端标识封装为Principal对象,从而让服务端能通过getName()方法找到指定客户端
Object o = attributes.get("name");
return new FastPrincipal(o.toString());
}
}).addInterceptors(new HandleShakeInterceptors()).setAllowedOrigins("*");//.withSockJS() 注册两个STOMP的endpoint,分别用于广播和点对点
}
/**
* 这是用于配置服务器向浏览器发送的消息。 clientOut就表示出出口。还有一个inBoundChannel用于处理浏览器向服务器发送的消息
* corePoolSize(1)处理的工作线程设置1,阻塞保证消息时序性,期待更好的解决方案(比如多个消费者动态创建多个queue)
*
* @param registration
*/
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(1).maxPoolSize(1);
}
// 定义一个自己的权限验证类
class FastPrincipal implements Principal {
private final String name;
public FastPrincipal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
HandleShakeInterceptors.java
import java.util.Map;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
/**
* 检查握手请求和响应, 对WebSocketHandler传递属性
*/
public class HandleShakeInterceptors implements HandshakeInterceptor {
/**
* 在握手之前执行该方法, 继续握手返回true, 中断握手返回false.
* 通过attributes参数设置WebSocketSession的属性
*
* @param request
* @param response
* @param wsHandler
* @param attributes
* @return
* @throws Exception
*/
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map attributes) throws Exception {
String name= ((ServletServerHttpRequest) request).getServletRequest().getParameter("name");
//保存客户端标识
attributes.put("name", "caopc");
return true;
}
/**
* 在握手之后执行该方法. 无论是否握手成功都指明了响应状态码和相应头.
*
* @param request
* @param response
* @param wsHandler
* @param exception
*/
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception exception) {
}
}
web端访问的controller
@Controller
public class SubController {
@Autowired
public SimpMessagingTemplate template;
@MessageMapping("/subscribe")
public void subscribe(ReceiveMessage rm) {
for(int i =1;i<=20;i++) {
//广播使用convertAndSend方法,第一个参数为目的地,和js中订阅的目的地要一致
template.convertAndSend("/topic/getResponse", rm.getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@MessageMapping("/queue")
//public void queue(ReceiveMessage rm) {
public void queue(Principal principal,Message message) throws UnsupportedEncodingException {
/*广播使用convertAndSendToUser方法,第一个参数为用户id,此时js中的订阅地址为
"/user/" + 用户Id + "/message",其中"/user"是固定的*/
byte[] messageInByte = message.getPayload();
System.out.println(new String(messageInByte,"utf-8"));
//parseMessage(new String(messageInByte,"utf-8"));
template.convertAndSendToUser("userid","/message",messageInByte);
}
然后是queue.html,转换方法可以不用在意,是lz测试时候使用的
Hello queue
用户Id
控制消息
topic.html
Hello topic
UserId
application配置文件只配置rabbitmq地址即可
server.port=8989
spring.application.name=xxxx
#spring.rabbitmq.host= 40.122.118.224
#spring.rabbitmq.port= 5672
#spring.rabbitmq.username=xxx
#spring.rabbitmq.password=xxxx
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false