集群方案如下:
- 采用Redis的订阅与发布,由于Websocket无法被序列化,不能进行缓存,所以不能直接将websocket消息缓存到Redis中。
- 采用单纯的RabbitMQ,利用fanouttopic进行消息订阅,将Websocket消息结果发送到消息队列中,在进行转发接收。参考代码
- 采用RabbitMQ+MQTT消息协议,可以在RabbitMQ官网上看到
- 采用RabbitMQ+STOMP消息协议,可以在RabbitMQ官网上看到【推荐使用】
- 还能够利用负载均衡的源地址哈希法,将ip通过一定的hash算法转发到一台固定的服务器(这个的话,对代码几乎没有改动,不过缺点也比较大)
接下来介绍如何使用RabbitMQ+STOMP,代码如下
maven配置文件org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-tomcatprovided org.springframework.boot spring-boot-starter-testtest org.junit.vintage junit-vintage-engineorg.springframework.boot spring-boot-starter-websocketorg.webjars webjars-locator-coreorg.webjars sockjs-client1.0.2 org.webjars stomp-websocket2.3.3 org.springframework.boot spring-boot-starter-amqpcommons-lang commons-lang2.6
spring:
rabbitmq:
host: 192.168.66.10
port: 5672
username: guest
password: guest
RabbitMQ配置类
@Configuration
public class RabbitConfig {
@Bean
public Queue helloQueue() {
return new Queue("hello");
}
}
Websocket配置类
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic","/all");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
}
}
接收消息并发送
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@RestController
public class WebSocketTestController {
@Autowired
private SimpMessagingTemplate messagingTemplate;
//RequestMessage消息结果集
@MessageMapping("/chat")
public void messageHandling(RequestMessage requestMessage) throws Exception {
String destination = "/topic/" + HtmlUtils.htmlEscape(requestMessage.getRoom());//htmlEscape 转换为HTML转义字符表示
String content = HtmlUtils.htmlEscape(requestMessage.getContent());
System.out.println( requestMessage.getRoom() );
System.out.println( content );
messagingTemplate.convertAndSend(destination, requestMessage);
}
}
前端页面
My WebSocket
频道号:
做题区:
频道号:



