0
点赞
收藏
分享

微信扫一扫

基于redis GEO实现查找附近的门店

巧乐兹_d41f 2022-01-06 阅读 29

1.导入jar包

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

2.配置 配置文件

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=300ms
@RestController
public class GeoController {
    @Autowired
    private GeoService geoService;

    /**
     * 根据指定经纬度查询附件的店铺
     * @return
     */
    @GetMapping(value = "/test")
    public List<ShopVO> radiusByxy(){
        //这个坐标是北京王府井的位置
        Circle circle=new Circle(116.418017,39.914402, Metrics.KILOMETERS.getMultiplier());

        return geoService.findRecentlyShop(circle);
    }
}

@Service
public class GeoService {
    private static final String CITY="city";
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 初始化经纬度数据
     */
    @PostConstruct
    public void initGeoData(){
        Map<String, Point> map=new HashMap<>();
        map.put("天安门",new Point(116.403963,39.915119));
        map.put("故宫",new Point(116.403414 ,39.924091));
        map.put("长城",new Point(116.024067,40.362639));
        redisTemplate.opsForGeo().add(CITY,map);
    }

    public List<ShopVO> findRecentlyShop(Circle circle) {
        /**
         *  返回50条数据
         *  includeDistance 包含距离
         *  includeCoordinates 包含经纬度
         *  sortAscending 正序排序
         *  limit 限定返回的记录数
         *
         */


            RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(50);
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = redisTemplate.opsForGeo().radius(CITY, circle, args);
        List<ShopVO> shopVOList=new ArrayList<>();
        geoResults.forEach(item->{
            RedisGeoCommands.GeoLocation<String> location = item.getContent();
            Point point = location.getPoint();
            ShopVO shopVO = ShopVO.builder().shopName(location.getName()).lng(point.getX()).lat(point.getY()).build();
            shopVOList.add(shopVO);
        });
        return shopVOList;
    }
}

/**
 * 店铺信息
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ShopVO {
    /**
     * 店铺名称
     */
    private String shopName;
    private Double lng;
    private Double lat;
}

举报

相关推荐

0 条评论