springboot 集成websocket

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

	前提:引入Websocket包
	
	     org.springframework.boot
	     spring-boot-starter-websocket
	 
  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;

    }

你可能感兴趣的:(spring,boot,websocket,后端)