Spring boot + Websocket 再篇

package com.demo.config;

import com.demo.entity.CustomSpringConfigurator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator {
    @Bean
    public CustomSpringConfigurator customSpringConfigurator(){
        return new CustomSpringConfigurator();
    }
}


package com.demo.entity;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContextAware;

import javax.websocket.server.ServerEndpointConfig;

public class CustomSpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
    private static volatile BeanFactory context;

    @Override
    public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) throws BeansException {
        CustomSpringConfigurator.context = applicationContext;
    }

    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return context.getBean(clazz);
    }
}


package com.demo.entity;

import com.demo.service.PerfService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Timer;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket-endpoint", configurator = CustomSpringConfigurator.class)
@Component
public class OwnWebSocket {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static CopyOnWriteArraySet<OwnWebSocket> webSockets = new CopyOnWriteArraySet<>();

    private Session session;
    @Autowired
    private PerfService perfService;
    private Timer timer;

    @OnOpen
    public void onOpen(Session session) throws IOException{
        this.session = session;
        webSockets.add(this);
        timer = new Timer(true);
        long delay = 0l;
        TimerDBTask dbTask = new TimerDBTask(session, perfService);
        timer.schedule(dbTask, delay, 60000);
    }

    @OnClose
    public void onClose() throws IOException{
        webSockets.remove(this);
    }

    @OnError
    public void onError(Throwable throwable) throws IOException{
        logger.info("异常发生...");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值