spring boot2.0.5+jpa+websocket

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37279783/article/details/82379395
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
单线程管理websocket连接

//@ServerEndpoint("/websocket/{user}")
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
    private static   final Log log = LogFactory.getLog(WebSocketServer.class);
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    //单线程管理
    AisThread aisThread = new AisThread();
    Thread thread = new Thread(aisThread);

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
//            sendMessage("连接成功");
            thread.start();
        } catch (Exception e) {
            log.error("websocket IO异常");
        }
    }
    //	//连接打开时执行
    //	@OnOpen
    //	public void onOpen(@PathParam("user") String user, Session session) {
    //		currentUser = user;
    //		System.out.println("Connected ... " + session.getId());
    //	}

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
            aisThread.stopMe();
            webSocketSet.remove(this);  //从set中删除
            subOnlineCount();           //在线数减1
            log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message) {
        log.info("来自客户端的消息:" + message);

        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        log.info(message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

 自定义类中注入bean,实现业务操作,获取集合对象用fastjson转换成json字符串:

@Component
public class AisThread implements Runnable{

    @Autowired
    AisDayService aisDayService;
    private static AisThread  aisThread ;
    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        aisThread = this;
        aisThread.aisDayService = this.aisDayService;
        // 初使化时将已静态化的testService实例化
    }
    boolean stopMe = true;
    public void stopMe() {
        stopMe = false;
    }

    @Override
    public void run() {
        WebSocketServer webSocketServer = new WebSocketServer();
        while (stopMe){
            try {
            List<AisJkxxbDay> aisJkxxbDays = aisThread.aisDayService.findAll();
            JSONArray array= JSONArray.parseArray(JSON.toJSONString(aisJkxxbDays));
            webSocketServer.onMessage(array.toJSONString());
            Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
h5
<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        //建立连接,这里的/websocket ,是ManagerServlet中开头注解中的那个值
        websocket = new WebSocket("ws://192.168.1.125:8080/websocket");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }
    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };
    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }
    //连接关闭的回调方法
    websocket.onclose = function () {
        alert(1);
        setMessageInnerHTML("WebSocket连接关闭");
    }
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML = innerHTML;
    }
    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }
</script>
将fastjson的jar包复制入项目lib文件夹,在pom文件中如下配置导入
<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.49</version>
			<scope>system</scope>
			<systemPath>${project.basedir}/lib/fastjson-1.2.49.jar</systemPath>
		</dependency>

在构建中加入configuration,打包时可以将fastjson一起打包
<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<includeSystemScope>true</includeSystemScope>
				</configuration>
			</plugin>
		</plugins>
	</build>

猜你喜欢

转载自blog.csdn.net/qq_37279783/article/details/82379395