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("異常發生...");
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章