package com.ydtech.modules.admin.service; import cn.hutool.core.collection.CollectionUtil; import com.ydtech.modules.admin.model.SysGeographyPosition; import com.ydtech.modules.admin.model.po.SysPcAddress; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.geo.*; import org.springframework.data.redis.connection.RedisGeoCommands; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Service public class GeoService { @Autowired private RedisTemplate redisTemplate; // 添加位置 public void addLocation(String geoKey,String userId, double longitude, double latitude) { redisTemplate.opsForGeo().add(geoKey, new Point(longitude, latitude), userId); } // 批量添加位置 public void addLocations(List list, String geoKey) { for (SysPcAddress location : list) { addLocation(geoKey,location.getUserId(),Double.parseDouble(location.getLongitude()) , Double.parseDouble(location.getLatitude())); } } public void addLocationGeography(List list, String geoKey) { for (SysGeographyPosition location : list) { addLocation(geoKey,location.getId(),Double.parseDouble(location.getLongitude()) , Double.parseDouble(location.getLatitude())); } } public void move(List list, String geoKey) { for (String location : list) { redisTemplate.opsForGeo().remove(geoKey,location); } } // 查找某位置附近的ID集合 public List findNearbyIds(String geoKey, double longitude, double latitude, double radius) { Circle within = new Circle(new Point(longitude, latitude), new Distance(radius, Metrics.NEUTRAL)); RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeCoordinates().includeDistance(); List>> content = redisTemplate.opsForGeo().radius(geoKey, within, args).getContent(); if (content .size()==0) return new ArrayList(); return content.stream() .map(result -> result.getContent().getName()) .collect(Collectors.toList()); } }