VUE相关文章

vue+stomp/websocket+springboot

2019-06-06  本文已影响0人  jianshuqiang

主要是实现vue+stomp+springboot的整合demo,功能目前还不完善
vue部分
一、引入vue依赖

npm install sockjs-client
npm install stompjs
npm install net
npm install vue-stomp

二、

<template>
  <div class="">、
    <h1>Stock Price</h1>
    <div>
      <button @click="senMessage">发送消息</button>
      <ul>
        <li v-for="m in list1" :key="m.name">{{ m.name }}: {{ m.price }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
export default {
  data() {
    return {
      list1: [],
      stompClient: null

    }
  },
  mounted() {
    this.initWebSocket()
  },
  methods: {
    senMessage() {
      this.stompClient.send('/app/hello')
    },
    initWebSocket() {
      this.connection()
      // 需要有一个失败重连得到问题
    },
    connection() {
      // 更换that指针
      const socket = new SockJS('http://localhost:60000/webSocket')
      this.stompClient = Stomp.over(socket)
//建立连接,订阅主题
      this.stompClient.connect({}, (frame) => {
        console.log(frame)
        this.stompClient.subscribe('/topic/getResponse', (val) => {
          // this.list1 = JSON.parse(val.body)
          console.log('-------++++++++++++++++++++++++++++++------------')
//下面会报错,应该是json的问题,但是数据可以接收到
          console.log(val.body)
        })
      })
      // 回调函数 3 end
    }
  }
}
</script>

springboot
一、映入websocket的依赖

  <!--使用websocket作为数据推送-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、配置websocket

package com.sgcc.dls.imnotice.config;

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;

/**
 * @author zhangqiang
 * @title WebSocketConfig
 * @Description 描述 websocket的配置类 开启 ServerPoint
 * @Date 2019年06月05日 10:57
 * @Copyright 2019-2020 www.epri.sgcc.com.cn All rights reserved.
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    /**
     * 注册stomp端点,主要是起到连接作用
     *
     * @param stompEndpointRegistry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry
                .addEndpoint("/webSocket")  //端点名称
                //.setHandshakeHandler() 握手处理,主要是连接的时候认证获取其他数据验证等
                //.addInterceptors() 拦截处理,和http拦截类似
                .setAllowedOrigins("*") //跨域
                .withSockJS(); //使用sockJS

    }

    /**
     * 注册相关服务
     *
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //这里使用的是内存模式,生产环境可以使用rabbitmq或者其他mq。
        //这里注册两个,主要是目的是将广播和队列分开。
        //registry.enableStompBrokerRelay().setRelayHost().setRelayPort() 其他方式
        registry.enableSimpleBroker("/topic");
        //设置客户端前缀 即@MessageMapping
        registry.setApplicationDestinationPrefixes("/app");
        //点对点发送前缀
        registry.setUserDestinationPrefix("/user");
    }

}

三、配置跨域问题(此处针对前后端分离)

package com.sgcc.dls.imnotice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author zhangqiang
 * @title CorsConfig 如果使用网关服务调用微服务,则注释掉Configuration注解;如果不使用网关服务,则需将Configuration注解的注释放开
 * @Description 配置跨域问题
 * @Date 2019年05月28日 15:02
 * @Copyright 2019-2020 www.epri.sgcc.com.cn All rights reserved.
 */
@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许任何域名访问
        corsConfiguration.addAllowedOrigin("*");
        //允许任何header访问
        corsConfiguration.addAllowedHeader("*");
        //允许任何方法访问
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

四、代码

package com.sgcc.dls.imnotice.controller;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WebsocketController {
    @MessageMapping("/test")
    public String test(String data) {
        return "测试成功";
    }

    /**
     * @param null:
     * @return
     * @description 方法描述 根据设置此处应该是 app/hello
     * /topic/getResponse 为订阅
     * @author zhangqiang
     * @date 2019年06月06日 17:03
     */
    @MessageMapping("/hello")
    @SendTo("/topic/getResponse")
    public String sub() throws InterruptedException {
        Thread.sleep(1000);
        return "感谢您订阅了我";
    }

    @MessageMapping("welcome")
    public String say() throws Exception {
        Thread.sleep(1000);
        return "成功";
    }

    @MessageMapping("/message")
    @SendToUser("/message")
    public String userGetMessage() {
        return "message";

    }

}

后续将继续完善

上一篇 下一篇

猜你喜欢

热点阅读