Spring boot + Websocket 再篇

来源:互联网 发布:汽车分期2016年数据 编辑:程序博客网 时间:2024/05/18 03:05
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@Configurationpublic 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)@Componentpublic 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("异常发生...");    }}


原创粉丝点击