@Service
public class MovementDetectionService {
private static final double MOVEMENT_THRESHOLD = 10.0; // 移动阈值(米)
private static final long TIME_THRESHOLD = 60000; // 时间阈值(毫秒)
private final Map<String, LocationMessage> lastLocations = new ConcurrentHashMap<>();
public MovementStatus detectMovement(LocationMessage newLocation) {
LocationMessage lastLocation = lastLocations.get(newLocation.getDeviceId());
if (lastLocation == null) {
lastLocations.put(newLocation.getDeviceId(), newLocation);
return MovementStatus.UNKNOWN;
}
double distance = LocationUtils.calculateDistance(
lastLocation.getLatitude(), lastLocation.getLongitude(),
newLocation.getLatitude(), newLocation.getLongitude()
);
long timeDiff = newLocation.getTimestamp() - lastLocation.getTimestamp();
// 更新最新位置
lastLocations.put(newLocation.getDeviceId(), newLocation);
if (timeDiff > TIME_THRESHOLD) {
if (distance > MOVEMENT_THRESHOLD) {
return MovementStatus.MOVING;
} else {
return MovementStatus.STATIONARY;
}
}
return MovementStatus.UNKNOWN;
}
}
创建一个枚举类表示移动状态:
java
public enum MovementStatus {
MOVING,
STATIONARY,
UNKNOWN
}
最后创建RabbitMQ消息监听器:
java
@Component
public class LocationMessageListener {
private final MovementDetectionService movementDetectionService;
@Autowired
public LocationMessageListener(MovementDetectionService movementDetectionService) {
this.movementDetectionService = movementDetectionService;
}
@RabbitListener(queues = "location.queue")
public void handleLocationMessage(LocationMessage message) {
MovementStatus status = movementDetectionService.detectMovement(message);
switch (status) {
case MOVING:
System.out.println("设备 " + message.getDeviceId() + " 正在移动");
break;
case STATIONARY:
System.out.println("设备 " + message.getDeviceId() + " 处于静止状态");
break;
case UNKNOWN:
System.out.println("设备 " + message.getDeviceId() + " 状态未知");
break;
}
}
}
RabbitMQ配置类:
java
@Configuration
public class RabbitMQConfig {
@Bean
public Queue locationQueue() {
return new Queue("location.queue", true);
}
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setMessageConverter(jsonMessageConverter());
return template;
}
}