webSocket发送给小程序用户的消息异步推送

webSocket发送给小程序用户的消息异步推送_第1张图片

1.首先后端创建一个WebSocketConfig 配置类

@Configuration
public class WebSocketConfig {
    /**
     * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

2.之后创建一个websoket 连接收发类

package com.skyable.smartlife.lock.config;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.alibaba.fastjson.JSON;
import com.skyable.smartlife.constant.BaseConstant;
import com.skyable.smartlife.constant.ExceptionConstant;
import com.skyable.smartlife.exception.CloudException;
import com.skyable.smartlife.lock.entity.lockEvent.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author Administrator
 */
@ServerEndpoint("/webSocket/notice/{userId}")
@Component
@Slf4j
public class WebSocketServer {
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        log.info("-----onOpen-------" + userId);
        this.session = session;
        this.userId = userId;
        onClose();
        webSocketMap.put(userId, this);
        try {
            WebSocket webSocket = new WebSocket(BaseConstant.NOTICE_TYPE_0, "连接成功");
            log.info("连接成功");
            sendMessage(JSON.toJSONString(webSocket));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info(userId + "onClose");
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
        }
    }

    /**
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        synchronized (this.session) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) {
        log.info("----------------webSocketMap---------------" + webSocketMap + "-------" + webSocketMap.containsKey(userId));
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            try {
                webSocketMap.get(userId).sendMessage(message);
                log.info("消息发送成功!!!" + userId);
            } catch (IOException e) {
                e.printStackTrace();
                throw new CloudException(ExceptionConstant.WEBSOCKET_SEND_ERROR);
            }
        } else {
            log.info("----消息发生失败----存入的对象" + webSocketMap + "--" + userId + "---");
        }
    }
}

3.异步推送消息

package com.skyable.smartlife.lock.service.impl;

import com.alibaba.fastjson.JSON;
import com.skyable.smartlife.constant.BaseConstant;
import com.skyable.smartlife.lock.config.WebSocketServer;
import com.skyable.smartlife.lock.entity.lockEvent.LockEvent;
import com.skyable.smartlife.lock.mapper.LockEventMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



/**
 * 异步方法的服务, 不影响主程序运行。
 *
 * @author Administrator
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class AsyncServiceImpl {
    private final LockEventMapper lockEventMapper;

    /**
     * 发送微信推送消息
     */
    @Async(value = "dataCollectionExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void sendUserIdMsg(LockEvent lockEvent, String userId) {
        WebSocketServer.sendInfo(JSON.toJSONString(lockEvent), userId);
        //存入通知表
        lockEventMapper.insertNotice(Long.parseLong(userId),
                lockEvent.getDeviceId(),
                lockEvent.getContent(),
                lockEvent.getType(),
                BaseConstant.READ_STATUS_1,
                lockEvent.getCreateTime());
        log.info("存入通知表成功");
    }
}

4.异步推送

 List lockUserIdList = lockUserMapper.selectUserList(deviceId);
        //websocket发送消息给前端
        lockUserIdList.forEach((userId) -> {
            try {
                // 异步调用,使用线程池。
                asyncService.sendUserIdMsg(lockEvent, userId.toString());
            } catch (Exception ex) {
                log.error("微信推送消息通知异常", ex);
            }
        });

你可能感兴趣的:(多线程,微信小程序,websocket,网络协议,网络)