websocket中使用service

socket中引入service层

@ServerEndpoint("/chat/room/group/{param}")
@Component
@Slf4j
public class MyWebsocketServer {
    //错误引用
    //@Autowired
    // private SocketUserService socketUserService;
    
    //错误引用
    // ApplicationContext act = ApplicationContextRegister.getApplicationContext();
    // SocketUserService socketUserService = act.getBean(SocketUserService.class);
    
    // 正确引用
    public static SocketUserService socketUserService;
    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();
    private Gson gson = new Gson();

    @OnOpen
    public void onOpen(Session session,@PathParam("param")String socketUserId) {
        log.info("有新的客户端连接了: {}", session.getId());
        SocketUser socketUser = socketUserService.getSocketUser(Long.valueOf(socketUserId));
         System.out.println(socketUser);
    }
}

在配置类中写入

@Configuration
public class WebsocketConfiguration {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
	//添加下面配置 在socket引入socketUserService
    @Autowired
    public void socketUserService(SocketUserService socketUserService){
        MyWebsocketServer.socketUserService = socketUserService;
    }
}

注意:这步写完有极大可能报错

could not initialize proxy - no Session

错误解析

  • 去网上找资料,就是说因为 hibernate(这里是 Spring Data JPA ) 跟 spring 整合以后,hibernate 的 session 就交给 spring 管理了,请求进来的时候打开 session,请求完成的时候关闭 session。当我们想要使用懒加载去获取数据的时候,这时候原先的那个 session 已经关闭了,不能再获取数据了。由此,spring专门为这种情况作了一个过滤器 org.springframework.orm.hibernate4.support.OpenSessionInViewFilter。它可以把hibernate的session的声明周期维持在视图的开启和关闭之间。这样,只要我们这个视图没有关闭,我们就可以通过 ajax 来使用懒加载获取数据

解决错误

  • 在配置文件中加入
  1. .yml配置
spring:
  jpa:
    properties:
      hibernate:
        enable_lazy_load_no_trans: true
  1. .properties配置
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值