springboot 集成websocket

发布时间:2024年01月19日

当前java项目普遍使用两种方式集成Websocket,一种是依赖Tomcat,一种是springboot内置的,本文采用springboot内置方案。

	前提:引入Websocket包
	<dependency>
	     <groupId>org.springframework.boot</groupId>
	     <artifactId>spring-boot-starter-websocket</artifactId>
	 </dependency>
  1. 定义WebSocketConfig

     @Configuration
     @EnableWebSocket
     public class WebSocketConfig implements WebSocketConfigurer {
     
         @Autowired
         private CustomWebSocketHandler customWebSocketHandler;
     
         @Override
         public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
             registry.addHandler(customWebSocketHandler, "/ws").setAllowedOrigins("*");
         }
     }
    

2.定义WebSocketHandler

	/**
	 * 创建一个WebSocket请求控制器,来处理websocket通信的对话服务
	 */
	@Slf4j
	@Component
	public class CustomWebSocketHandler extends TextWebSocketHandler {
	   
	  	@Override
	    public void afterConnectionEstablished(@NotNull WebSocketSession session) {
	        log.info("CustomWebSocketHandler.afterConnectionEstablished.对话服务的websocket连接成功,session={}", session);
	        // 在连接建立后发送消息到服务器(可选)
	        // session.sendMessage(new TextMessage("Hello, server!"));
	    }
	 	
		 @Override
   		 public void handleTextMessage(@NotNull WebSocketSession session, TextMessage message) {
			log.info("CustomWebSocketHandler.handleTextMessage.websocket接收到消息,session={},message={}", session, message.getPayload());
			//在这里写自己的业务逻辑
		 }
	
		 @Override
	 	 public void handleTransportError(@NotNull WebSocketSession session, @NotNull Throwable ex) {
	        log.error("CustomWebSocketHandler.handleTransportError.对话服务的websocket连接异常,session={}", session, ex);
	        try {
	            if (session.isOpen()) {
	                log.error("CustomWebSocketHandler.handleTransportError.消息发送失败,websocket连接主动关闭,session={}", session);
	                session.close();
	            }
	        } catch (IOException e) {
	            throw new RuntimeException(e);
	        }
	    }
	}

3.此时就算集成完毕了,本地客户端可以正常调用了,可以使用AiFox工具,个人觉得比postman更好用

4.如果是正式环境使用了nginx,需要添加如下配置:

	location /ai-service-center/ws  {
      proxy_pass   http://localhost:30861/ws;
      proxy_read_timeout 300s;
      proxy_send_timeout 300s;
      proxy_http_version 1.1;
      proxy_pass_request_headers on;
      proxy_buffering off;
      proxy_cache off;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;

    }
文章来源:https://blog.csdn.net/weixin_43945983/article/details/135697961
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。