Springboot+VUE 基于socket实现数据实时刷新

一、pom.xml加入依赖
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、注入ServerEndpointExporter

      @Configuration
      public class WebSocketConfig
      {
          /**
            * 注入ServerEndpointExporter,
            * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
         */
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
           return new ServerEndpointExporter();
        }
     }
三、发布socket服务

    @Component
@ServerEndpoint("/websocket/{shopId}")
public class WebSocket
{
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();
    
    @OnOpen
    public void onOpen(Session session, @PathParam(value="shopId")String shopId) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(shopId, session);
        System.out.println("【websocket消息】有新的连接,总数为:"+webSockets.size());
    }
    
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
    }
    
    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }
    
    // 此为广播消息
    public void sendAllMessage(String message) {
        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    // 此为单点消息
    public void sendOneMessage(String shopId, String message) {
        Session session = sessionPool.get(shopId);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

四、实现实时刷新的二种方式,前端定时刷新就不提了:

    1)通知方式
            当数据变化时,可通过调用http服务(controller调用了webSocket方法)通知页面socket客户端更新数据;      

        @RestController 
        @RequestMapping("socket") 
        public class SocketController
        {
              @Autowired
              private WebSocket webSocket;

              @RequestMapping("/sendAllWebSocket")
              public String test() {    
                   webSocket.sendAllMessage("{\"data\":\"清晨起来打开窗,心情美美哒~\"}");
                   return "websocket群体发送!";        
               }
    
              @RequestMapping("/sendOneWebSocket")
              public String sendOneWebSocket() {
                  webSocket.sendOneMessage("DPS007", "{\"data\":\"只要你乖给你买条gai!\"}");
                  return "websocket单人发送";
               }
        }
       2)后台轮训方式:后台启动定时任务,看数据是否变化(可获取数据最新id比较),然后再通过调用webSocket通知页面客户端刷新数据;

           @EnableScheduling  定时计划执行方法

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值