LocationPushService.java 2.19 KB
package com.diligrp.rider.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.diligrp.rider.vo.AdminRiderLocationVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
@RequiredArgsConstructor
@Slf4j
public class LocationPushService {

    private final LocationSessionRegistry sessionRegistry;
    private final ObjectMapper objectMapper;

    public void pushRiderLocation(AdminRiderLocationVO location) {
        if (location == null || location.getCityId() == null) {
            return;
        }
        LocationPushMessage message = new LocationPushMessage();
        message.setType("rider_location_update");
        message.setRiderId(location.getRiderId());
        message.setRiderName(location.getRiderName());
        message.setCityId(location.getCityId());
        message.setLng(location.getLng());
        message.setLat(location.getLat());
        message.setUpdateTime(location.getUpdateTime());
        broadcast(location.getCityId(), message);
    }

    public void pushConnected(Long cityId) {
        if (cityId == null) {
            return;
        }
        LocationPushMessage message = new LocationPushMessage();
        message.setType("connected");
        message.setCityId(cityId);
        broadcast(cityId, message);
    }

    private void broadcast(Long cityId, LocationPushMessage message) {
        try {
            String payload = objectMapper.writeValueAsString(message);
            for (WebSocketSession session : sessionRegistry.getSessions(cityId)) {
                if (!session.isOpen()) {
                    sessionRegistry.unregister(session);
                    continue;
                }
                synchronized (session) {
                    session.sendMessage(new TextMessage(payload));
                }
            }
            log.debug("骑手位置推送完成,cityId={} type={}", cityId, message.getType());
        } catch (Exception e) {
            log.warn("骑手位置推送失败,cityId={} type={}", cityId, message.getType(), e);
        }
    }
}