Springboot WebSocket STOMP協(xié)議

1.pom文件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2.配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketSTMPconfiguration extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    //注冊STOMP協(xié)議的節(jié)點(endpoint),并映射指定的url
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //注冊一個STOMP的endpoint,并指定使用SockJS協(xié)議
        registry.addEndpoint("/endpointOyzc").setAllowedOrigins("*").withSockJS();
    }
    @Override
    //配置消息代理(Message Broker)
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //點對點應(yīng)配置一個/user消息代理,廣播式應(yīng)配置一個/topic消息代理
        registry.enableSimpleBroker("/topic","/user");
        //點對點使用的訂閱前綴(客戶端訂閱路徑上會體現(xiàn)出來),不設(shè)置的話,默認也是/user/
        registry.setUserDestinationPrefix("/user");
    }
}

3.websocket代碼

@Component
@Slf4j
public class WebSocketSTOMPController {
    @Autowired
    private SimpMessagingTemplate template;

    //廣播推送消息
    @Scheduled(fixedRate = 3000)   // 每3秒鐘執(zhí)行一次,需要在 程序入口 @EnableScheduling,及該類添加注解 @Component
    public void sendTopicMessage() {
        System.out.println("后臺廣播推送!");
        User user=new User();
        //user.setUserName("oyzc");
        user.setReal_name("testusername123");
        user.setAccount("testaccount");
        //user.setAge(10);
        this.template.convertAndSendToUser("123abc","/queue/getResponse",user);
    }
}

3.使用

npm install stompjs 
npm install sockjs-client

<script>
import SockJS from  'sockjs-client';
import  Stomp  from 'stompjs';
export default {
    data(){
        return{
             path:"ws://x.x.x.x:8900/test",
            socket:""
        }
    },
    mounted(){
        this._initwebscoket()
    },
    methods:{
        _initwebscoket(){
            if(typeof(WebSocket) === "undefined"){
                alert("您的瀏覽器不支持socket")
            }else{
                var socket = new SockJS('http://x.x.x.x:8900/endpointOyzc'); 
                var stompClient = Stomp.over(socket);//使用STMOP子協(xié)議的WebSocket客戶端
        stompClient.connect({},function(frame){//連接WebSocket服務(wù)端         
            console.log('Connected:' + frame);
            //通過stompClient.subscribe訂閱/topic/getResponse 目標(destination)發(fā)送的消息
            stompClient.subscribe('/user/123abc/queue/getResponse',function(response){
                console.log(response)
                var code=JSON.parse(response.body); 
                console.log(code)                               
                //showResponse(code)                
            });
        });
            }
        }}}
</script>

注意:前端先建立連接后,在調(diào)用后端接口出發(fā) 發(fā)送socket消息。避免造成接收不到消息

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容