javax.websocket 使用指南

除了https://blog.csdn.net/u011556070/article/details/105844786 的建立ws server方法之外这里再收录记载一种JSR356的方法javax.websocket

需要注意在这种方法中使用spring的bean会需要额外的工作

@Configuration
public class WebConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public WebSocketEndPoint webSocketEndPoint() {
        return new WebSocketEndPoint();
    }
}

@Slf4j
@ServerEndpoint(value = "/task/block/{taskId}")
public class WebSocketEndPoint {

    @OnOpen
    public void onOpen(@PathParam("taskId") String taskId, Session session) {
        log.info("taskId={} 链接websocket", taskId);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("sessionId={} 关闭websocket", session.getId());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("接受信息:" + message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("客户端错误:" + error.getMessage(), error);
    }
}

上述这种方法的优势会比spring websocket使用起来略微简单一点,但是无法在endpoint中直接用@Autowired注入bean, 原因是@ServerEndpoint的JSR356和spring的注入顺序的关系

如果想在endpoint中使用spring的DI需要自己写一个SpringContextUtil

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    //通过名字获取上下文中的bean
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    //通过名字获取上下文中的bean
    public static <T> T getBean(String name, Class<T> tClass) {
        return applicationContext.getBean(name, tClass);
    }

    //通过类型获取上下文中的bean
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

然后即可在使用如下方式注入所需要的bean, 例如

 private SomeHandler someHandler = SpringContextUtil.getBean(SomeHandler.class);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值