springboot+vue简单使用websokcet以及使用java作为client连接

项目最新开发消息跟踪,第一个版本是采用websocket实时推送消息到前台浏览器,简单使用样例记录。

1.pom中添加依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-websocket</artifactId>
   <version>${spring.boot.version}</version>
</dependency>

2.springboot+vue代码样例

Application需要添加@EnableWebSocket注解

@SpringBootApplication(scanBasePackages = {"com.dzj"})
@EnableWebSocket
public class PortalApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(PortalApplication.class, args);
    }
}

websocket配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

websocket服务端,开启一个websocket服务端

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/portal-websocket/{taskId}")
@Component
@Slf4j
public class TmWebSocket {

    @Getter
    private static Map<Integer, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * On Open
     *
     * @param session session
     * @param taskId task id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "taskId") Integer taskId) {
        if (sessionMap.containsKey(taskId)) {
            log.warn("there is already a browser websocket of taskId:{} connected.", taskId);
            return;
        }
        sessionMap.put(taskId, session);
        log.info("new browser websocket client of taskId:{} connected.", taskId);
    }

    /**
     * On close
     *
     * @param taskId task id
     */
    @OnClose
    public void onClose(@PathParam(value = "taskId") Integer taskId) {
        sessionMap.remove(taskId);
        log.info("browser websocket of taskId:{} disconnected.", taskId);
    }

    /**
     * On message
     *
     * @param message message
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("portal websocket server receive client message:{}", message);
    }

    /**
     * Error
     *
     * @param throwable throwable
     */
    @OnError
    public void error(Throwable throwable) {
        log.error("portal websocket server occurs exception:{}", throwable.getMessage());
    }

    /**
     * Send one message
     *
     * @param taskId task id
     * @param message message
     */
    public static void sendOneMessage(Integer taskId, String message) {
        Optional.ofNullable(sessionMap.get(taskId)).ifPresent(session -> {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                log.error("taskId:{} push to browser client occurs exception:{}", taskId, e.getMessage());
            }
        });
    }
}

前台vue,用的选项式api,页面中定义初始化方法,ws为定义的websocket变量

    initWebSocket() {
      if ('WebSocket' in window) {
        let wsUrl = window.location.host;
        let pathName = window.location.pathname;
        let index = pathName.substr(1).indexOf("/");
        let contextPath = pathName.substr(0,index+1);
        this.ws = new WebSocket("wss://" + wsUrl + contextPath + "/portal-websocket/" + this.task.taskId);
        this.ws.onopen = this.wsOnOpen;
        this.ws.onerror = this.wsOnError;
        this.ws.onmessage = this.wsOnMessage;
        this.ws.onclose = this.wsOnClose;
      } else {
        this.$message({
          message: '不支持websocket',
          type: 'error',
        });
      }
    },
    // 打开连接
    wsOnOpen(event) {
      this.$message({
        message: '连接服务端成功',
        type: 'success',
      });
    },
    // 接收信息
    wsOnMessage(event) {
      // vue中自定义一个变量serverMsg接收服务端消息
      this.serverMsg.push(JSON.parse(event.data));
    },
    // 关闭连接
    wsOnClose(event) {
    },
    // 监听错误事件
    wsOnError(event, event2) {
      this.$message({
        message: '连接服务端失败',
        type: 'error',
      });
    },
    // 发送消息给服务器端
    wsSendMessage() {
      // 未实现
    },

存在一个问题,当存在大量消息推送到前台时,前台实时展示消息会非常卡顿,采用了一个折中方法,前台js定义一个定时器,每秒执行,读取前台接收的消息,限制展示500条,但是体验非常不友好,会导致大量消息跳号,且消息滚动太快,每秒有大量消息时,根本来不及看,也无法支持往回看,第二版本不再使用wenbsocket,优化为前台每秒主动查询,支持动态查询速率和往回查看,后面有空再写出来。这里为折中方法,前台使用定时器。

// msgTimer为vue定义的定时器,serverMsg为浏览器接收到服务端的消息
// tableData为展示消息的表格,限制500条。
this.msgTimer = setInterval(() => {
  this.tableData.push(...this.serverMsg);
  this.serverMsg = [];
  if (this.tableData.length > 500) {
    let tableLen = this.tableData.length;
    this.tableData.splice(0, tableLen - 500);
  }
}, 1000);

退出页面时关闭websocket连接和定期器

activeClose() {
  if (this.ws) {
    this.ws.close();
  }
  if(this.msgTimer) {
    clearInterval(this.msgTimer);
  }
}beforeDestroy() {
  this.activeClose();
},

3.java作为客户端连接代码样例

这里是wss的连接,需要配置sslContext,读者可以根据自己项目配置来灵活更改。

import com.dzj.PortalContext;
import com.dzj.SSLProperties;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@Slf4j
@Component
@EnableScheduling
public class WebSocketClient extends Endpoint {
    @Qualifier("portalSslContext")
    @Autowired
    private SSLContext sslContext;

    @Autowired
    private SSLProperties sslProperties;

    @Autowired
    private PortalContext context;

    private final Map<String, Object> userProperties = new ConcurrentHashMap<>();

    private final HashMap<Integer, Session> sessions = new HashMap<>();

    /**
     * Init
     */
    @PostConstruct
    public void init() {
        userProperties.put("org.apache.tomcat.websocket.SSL_CONTEXT", sslContext);
        userProperties.put("org.apache.tomcat.websocket.SSL_PROTOCOLS",
            sslProperties.getVerifies().get(0).getSslProtocols());
    }

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        log.debug("open portal websocket client");
        session.addMessageHandler(new OnMessageHandler());
        for (Map.Entry<Integer, Session> entry : sessions.entrySet()) {
            if (entry.getValue().getId().equals(session.getId())) {
                entry.setValue(session);
                log.info("open portal websocket client, site id {}", entry.getKey());
                return;
            }
        }

        Integer siteId = context.getCurrentSiteId();
        if (siteId == null) {
            log.error("current site id is null, open session failed");
            return;
        }

        sessions.put(siteId, session);
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        log.debug("close portal websocket client");
        Integer siteId = null;
        for (Map.Entry<Integer, Session> entry : sessions.entrySet()) {
            if (entry.getValue().getId().equals(session.getId())) {
                siteId = entry.getKey();
                try {
                    entry.getValue().close();
                    log.info("close portal websocket client, site id {}", siteId);
                } catch (IOException e) {
                    log.info("close portal websocket client occurs exception:{}", e.getMessage());
                }
                break;
            }
        }
        if (siteId == null) {
            log.error("current site id is null, close session failed");
            return;
        }

        sessions.remove(siteId);
    }

    @Override
    public void onError(Session session, Throwable throwable) {
        log.error("portal websocket client occurs exception:{}", throwable.getMessage());
    }

    private static class OnMessageHandler implements MessageHandler.Partial<String> {
        @Override
        public void onMessage(String message, boolean last) {
            log.debug("receive message:{}", message);
            int start = message.indexOf(':') + 1;
            int end = message.indexOf(',', start);
            Integer taskId = Integer.valueOf(message.substring(start, end));
            TmWebSocket.sendOneMessage(taskId, message);
        }
    }

    /**
     * Monitor web socket client
     */
    @Scheduled(initialDelay = 1000, fixedDelay = 1000 * 10)
    public void monitorWebSocketClient() {
        Integer siteId = context.getCurrentSiteId();
        if (siteId == null) {
            log.debug("cluster id is null, return");
            return;
        }

        String address = context.getCurrentConfigServerAddress(siteId);
        if (StringUtils.isEmpty(address)) {
            log.debug("site id {}, current config server address is null, return", siteId);
            return;
        }

        Session session = sessions.get(siteId);
        if (session != null && session.isOpen()) {
            log.debug("site id {}, portal websocket client state is open", siteId);
            return;
        }

        try {
            log.info("portal websocket client start to connect to site id {}, config server address {}", siteId,
                address);
            String wssUrl = "wss://" + address + "/uap-cc/v1/cc-websocket";
            URI uri = URI.create(wssUrl);
            ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
            clientEndpointConfig.getUserProperties().putAll(userProperties);
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            sessions.put(siteId, container.connectToServer(this, clientEndpointConfig, uri));
            log.info("portal websocket client connects to site id {}, config server address {} successful", siteId,
                address);
        } catch (Exception e) {
            log.error("portal websocket client connects to site id {}, config server address {} occurs exception:{}",
                siteId, address, e.getMessage());
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值