栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Websocket + Scheduled 服务的实现 - JAVA

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Websocket + Scheduled 服务的实现 - JAVA

1、参考链接

https://www.bilibili.com/video/BV1r54y1D72U?from=search&seid=2193943377005329491&spm_id_from=333.337.0.0

2、注解的方式

服务端代码实现=

package com.zhangz.innokproject.config.websocket;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
//GetHttpInfosConfigurator 自定义实现可以从httprequest获取相关信息
//value = "/websocket/{client}" 可以用这种URL方式传参,@PathParam("client") String client获取url后面的参数
@ServerEndpoint(value = "/websocket",configurator = GetHttpInfosConfigurator.class)
public class DemoForWebsocket {
	//保存所有与服务端建立连接的客户端信息
    private static Map onlineClients = new ConcurrentHashMap<>();

    public static Map getOnlineClients() {
        return onlineClients;
    }

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
	//存放每个客户端的名称
    private String client;
    
    @OnOpen
    public void onOpen(Session session,EndpointConfig config) throws Exception{
        this.session = session;
        //String machine = (String) config.getUserProperties().get("machine");
      
    }

    
    @OnClose
    public void onClose() throws Exception{
        //从map中删除
        session.close();
        onlineClients.remove(client);
        log.info("离线客户端:"+client+"n在线客户端:"+onlineClients.toString());
    }

    
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        try {
            HashMap map = JSONObject.parseObject(message, HashMap.class);
            //取出客户端信息并保存当地
            String machine = map.get("machine");
            String type = map.get("type");
            log.info("==========="+type+"==========="+machine);
            this.client = type+"-"+machine;
            onlineClients.put(this.client,this);
            log.info("在线客户端:"+onlineClients.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    @OnError
    public void onError(Session session, Throwable error){
        error.printStackTrace();
    }


    
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }

}

3、配置websocket
package com.zhangz.innokproject.config.websocket;

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
    //ServerEndpointExporter主要作用是扫描@ServerEndpoint注解、
    public ServerEndpointExporter getEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

##4、 EndpointConfig配置类

package com.zhangz.innokproject.config.websocket;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

public class GetHttpInfosConfigurator extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map> parameterMap = request.getParameterMap();
        sec.getUserProperties().putAll(parameterMap);
        super.modifyHandshake(sec, request, response);
    }
}
5、定时推送客户端
package com.hlxd.innokproject.config.websocket;

import com.alibaba.fastjson.JSONObject;
import com.hlxd.innokproject.bean.MachineQuotoGroup;
import com.hlxd.innokproject.service.QuotoMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

@Service
@EnableScheduling
@Slf4j
public class WebSocketService {

    @Resource
    private QuotoMonitorService quotoMonitorService;


    @Scheduled(cron = "0 */1 * * * ?")
    public void getMachineInfo(){
        MachineQuotoGroup machineQuotoGroup = null;
        try {
            Map onlineClients = DemoForWebsocket.getOnlineClients();
            log.info("====onlineClients===="+onlineClients.size());
            if (onlineClients.isEmpty()) return;
            Set set = onlineClients.keySet();
            for (String key : set){
            	//machineQuotoGroup  =   实现自己的逻辑往客户端推 
                onlineClients.get(key).sendMessage(JSONObject.toJSONString(machineQuotoGroup));
            }
        } catch (Exception e) {
            log.info("====websocket=====异常=====");
            e.printStackTrace();
        }
    }
}

6、websocket在线工具

http://oktools.net/websocket

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/336645.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号