0
点赞
收藏
分享

微信扫一扫

【零基础学习CAPL】——XML工程创建与使用详解

拾光的Shelly 2024-11-12 阅读 6

在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
举报

相关推荐

0 条评论