webSocket 使用(spring boot)

1.开启websocket

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    private ElectricRecordHandler electricRecordHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(electricRecordHandler, "/wsElectricRecord")
                .setAllowedOrigins("*");
    }


}

2.websocket 方法实现

@Component
@Slf4j
public class ElectricRecordHandler extends TextWebSocketHandler {


    private static final ConcurrentHashMap<String, WebSocketSession> SESSION_HOLDER = new ConcurrentHashMap<>();
    @Resource
    private BrpPowerStationService brpPowerStationService;

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        TextMessage textMessage = new TextMessage("消息出去了");
        session.sendMessage(textMessage);
    }

    @Override
    public void afterConnectionEstablished(@NonNull WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        SESSION_HOLDER.put(session.getId(), session);
        if(log.isDebugEnabled()){
            log.debug("webSocket already connected:");
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        SESSION_HOLDER.remove(session.getId());
        if(log.isDebugEnabled()){
            log.debug("webSocket disConnect:");
        }
    }

    public void sendMessage(Object message, String type) {
        if(log.isDebugEnabled()){
            log.debug("记录进来了:{}",message);
        }
        if (!CollectionUtils.isEmpty(SESSION_HOLDER)) {
            SESSION_HOLDER.values().stream().forEach(session -> {
                try {
                    SocketResult result = new SocketResult();
                    result.setType(type);
                    if (Constants.ELECTRIC_RECORD.equals(type)) {
                        InTheElectricRecord inTheElectricRecord = JsonUtils.convertValue(message, InTheElectricRecord.class);
                        if(log.isDebugEnabled()){
                            log.debug("websocket 记录:{}",inTheElectricRecord);
                        }
                        ElectricRecord electricRecord = brpPowerStationService.crudAndFunction(brpPowerStationMapper -> {
                            return brpPowerStationMapper.getPowerStation(inTheElectricRecord.getStationNo());
                        });
                        if(UserHolderUtils.isOperator()){
                            String userId = UserHolderUtils.getUserId();
                            List<String> listNumber = brpPowerStationService.crudAndFunction(
                                    mapper -> {
                                        return mapper.findNumbersByUserId(userId);
                                    }
                            );
                            if(CollectionUtils.isEmpty(listNumber)
                                    || !listNumber.contains(electricRecord.getNumber())){
                                electricRecord = null;
                            }
                        }
                        if (electricRecord != null) {
                            electricRecord.setStopTime(inTheElectricRecord.getStopTime());
                            electricRecord.setVin(inTheElectricRecord.getVin());
                        }
                        result.setContent(electricRecord);
                    }
                    TextMessage textMessage = new TextMessage(JsonUtils.objToJsonStr(result));
                    session.sendMessage(textMessage);
                    if(log.isDebugEnabled()){
                        log.debug("推送成功:{}",result.getContent());
                    }
                } catch (IOException e) {
                    log.error("发送消息失败", e);
                }
            });
        } else {
            log.info("session_holder 为空:{}",message);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
        super.handleTransportError(session,throwable);
        log.error("webSocket handleTransportError userId :{}",session.getId());
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值