spring-boot-starter-websocket创建服务

殷宾白
2023-12-01

WebSocketApplicationContextAware 层

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy(false)
public class WebSocketApplicationContextAware implements ApplicationContextAware {

    private static ApplicationContext APPLICATION_CONTEXT;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        APPLICATION_CONTEXT = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }
}

WebSocketConfig层

package com.dataexa.qt.websocket;

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

@Configuration
@EnableWebSocket
public class WebSocketConfig {

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

WebSocket类

@Slf4j
@Component  //注册到容器中
@ServerEndpoint("/webSocket")  //接收websocket请求路径
public class WebSocket {

    //定义一个websocket容器存储session,即存放所有在线的socket连接
    private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<>();

    private static ApplicationContext applicationContext = WebSocketApplicationContextAware.getApplicationContext();

    private Neo4jService neo4jService = (Neo4jService) applicationContext.getBean(Neo4jService.class);

 

    //处理连接建立
    @OnOpen
    public void opOpen(Session session) {
        log.info("【有新的客户端连接了】:{}", session.getId());
        //将新用户加入在线组
        webSocketSet.add(session);
        log.info("【websocket消息】有新的连接,总数:{}", webSocketSet.size());
   
    }


    @Value("${spring.socket.url}")
    private String url;

/*
这一段可加可不加  是用于连接socket的 相当与客户端
*/
    //启动链接第三方socket //监听在线状态 5 * * * * ? 5秒 , 0 0/5 * * * ? 5分钟
    @Scheduled(cron = "0 0/5 * * * ?")
    public  void webSocketStata(){
        try {
            BaseWebsocketClient baseWebsocketClient= new BaseWebsocketClient( new URI(url));
            baseWebsocketClient.connect();
            while (!baseWebsocketClient.getReadyState().equals(ReadyState.OPEN)){
                log.info("链接中....");
                Thread.sleep(1000);
                break;
            }
            log.info("状态 :{}",baseWebsocketClient.isOpen());
            JSONObject jsonObject=new JSONObject();
            if (baseWebsocketClient.isOpen()){
                jsonObject.put("code",5);
                jsonObject.put("data","green");
                sendMessage(jsonObject.toJSONString());
            }else {
                jsonObject.put("code",5);
                jsonObject.put("data","red");
                sendMessage(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    //处理连接关闭
    @OnClose
    public void Onclose(Session session) {
        webSocketSet.remove(session);
        log.info("【websocket消息】连接断开,总数:{}", webSocketSet.size());
    }

    //接受消息
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
        //根据用户发送回去
      session.getBasicRemote().sendText("发送信息");
    }

    //发消息调用即可
    public void sendMessage(String message) {
        try {
            for (Session session1 : webSocketSet) {
                session1.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}

依赖

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

启动类注解

@EnableScheduling 这是定时任务注解
@EnableWebSocket  socket注解

以上两者同时运用是就需要全部加上注解,单独之加单独即可.

 类似资料: