SpringBoot2.0与WebScoket集成实现后台向前台页面推送消息

使用Ajax也可以实现 通过定时实现向后台拉取数据 , 不过为了更加的优雅 采用WebScoket实现下

1.pom依赖


        
            org.springframework.boot
            spring-boot-starter-websocket
        

2.配置WebSocketConfig与WebSocketServer 两个java类  便于所有配置类的管理可以放在conf目录下


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

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

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.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
//访问服务端的url地址
@ServerEndpoint(value = "/websocket")
public class WebSocketServer {
    private static List sessions =  new CopyOnWriteArrayList();
    private Session session;
    /**
     * 连接建立成功调用的方法
     * */
    @OnOpen
    public void onOpen( Session session) throws IOException {
        System.out.println("this:"+this);
        sessions.add(session);
        this.session=session;
        session.getBasicRemote().sendText("欢迎使用webSocket连接到服务器...");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        sessions.remove(session);
    }
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }


//添加synchronized 保证线程安全 不然多条message一起发送 会报错的
    public static synchronized void sendtoAll(String message) throws IOException {
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.前台页面建立webscoket连接

 

你可能感兴趣的:(java,SpringBoot)