stomp spring ws接口调用

STOMP(Simple Text Oriented Messaging Protocol)是一种用于在客户端和服务器之间进行实时消息传递的简单文本协议。在Spring框架中,STOMP被用于创建交互式的Web应用程序,通过提供一个基于WebSocket通信的子协议来实现。这使得客户端和服务器之间能够进行异步消息传递,从而实现Web应用程序中的实时更新和通知。

stomp spring ws接口调用_第1张图片

这种方式比起websocket有一个非常好的特点,就是它可以使用几个注解就可以像接口编程一样。同时支持像ws一样全双工的操作方式或者像队列一样,发布订阅。当然也支持集成到队列进行一个交互。这里只是简单写了一个demo,后续进行深度解释其中的源码原理。

服务端

具体代码

package com.example.messagingstompwebsocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

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

		//基于内存的STOMP消息代理
//		registry.enableSimpleBroker("/queue", "/topic");

		//基于RabbitMQ 的STOMP消息代理
/*        registry.enableStompBrokerRelay("/queue", "/topic")
                .setRelayHost(host)
                .setRelayPort(port)
                .setClientLogin(userName)
                .setClientPasscode(password);*/

//		registry.setApplicationDestinationPrefixes("/app", "/foo");
		registry.setUserDestinationPrefix("/user");
	}

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
//		registry.addEndpoint("/gs-guide-websocket").withSockJS();
//		registry.addEndpoint("/webSocketServer").setAllowedOrigins("*").withSockJS();
		registry.addEndpoint("/webSocketServer")
				.withSockJS();
	}

}

客户端





  stomp
    



Welcome


最后

点赞关注评论一键三连,每周分享技术干货、开源项目、实战经验、国外优质文章翻译等,您的关注将是我的更新动力!

引用

Intro to WebSockets with Spring | Baeldung

STOMP_setapplicationdestinationprefixes-CSDN博客

你可能感兴趣的:(spring,java,后端)