欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > SpringBoot(十三)SpringBoot配置webSocket

SpringBoot(十三)SpringBoot配置webSocket

2025/4/20 4:28:10 来源:https://blog.csdn.net/qq_39708228/article/details/143688298  浏览:    关键词:SpringBoot(十三)SpringBoot配置webSocket

在PHP版本的博客中,我使用PHP+swoole实现了webscoket即时聊天的功能。

在java版本的博客中,我也想使用webscoket来实现即时聊天的功能,下边是我实现过程的一个记录。

一:在pom.xml中添加记录

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

二:在config目录添加WebSocketConfig.java文件

package com.springbootblog.config;
 
 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;
 /**
  * @ Description: 开启WebSocket支持
  */
 @Configuration
 @EnableWebSocket
 public class WebSocketConfig
 {
     @Bean
     public ServerEndpointExporter serverEndpointExporter() {
         return new ServerEndpointExporter();
     }
 }

三:解决@ServerEndpoint注解中的@Autowired注解失效的问题

原理是WebSocket是线程安全的,有用户连接时就会创建一个新的端点实例,一个端WebSocket是多对象的,使用的spring却是单例模式。这两者刚好冲突。

所以在@ServerEndpoint注解下不能使用Autowired注解注入对象,那我在webscoket的控制器中也是需要操作redis以及操作数据库的,那我该如何去处理这个问题呢?

我百思不得其解。最后在百度上一位大神的指点下解决了这个问题。

使用从容器中取对象的工具类

在utils目录中添加SpringUtil.java文件

package com.springbootblog.utils;
 
 import org.springframework.beans.BeansException;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationContextAware;
 import org.springframework.stereotype.Component;
 
 @Component
 public class SpringUtil implements ApplicationContextAware
 {
     private static ApplicationContext applicationContext;
 
     @Override
     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         SpringUtil.applicationContext = applicationContext;
     }
 
     public ApplicationContext getApplicationContext(){
         return applicationContext;
     }
 
     public static Object getBean(String beanName){
         return applicationContext.getBean(beanName);
     }
 
     public static <T> T getBean(Class<T> clazz){
         try
         {
             return (T)applicationContext.getBean(clazz);
         }
         catch(Exception e)
         {
             return null;
         }
     }
 }

四:在SpringBoot中使用webscoket

package com.springbootblog.controller.fontend;
 
 import com.alibaba.fastjson.JSONObject;
 import com.springbootblog.dao.ChatRecordDao;
 import com.springbootblog.dao.UserDao;
 i

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词