Redis基于Geo的地理位置操作

package com.example.redis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.domain.geo.Metrics;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class GEOTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test() {
        Map map = new HashMap<>();
        map.put("北京", new Point(116.403936, 39.915119));
        map.put("故宫", new Point(116.403414,39.924091));
        map.put("长城", new Point(116.024067,40.362639));
        redisTemplate.opsForGeo().add("city",map);

        // 获取坐标
        List position = redisTemplate.opsForGeo().position("city", "故宫");
        System.out.println(position);

        // 获取hash
        List geoHash = redisTemplate.opsForGeo().hash("city", "故宫");
        System.out.println(geoHash);

        // 获取距离
        Distance distance = redisTemplate.opsForGeo().distance("city", "故宫", "长城", RedisGeoCommands.DistanceUnit.KILOMETERS);
        System.out.println(distance);

        // 通过经纬度查找附近
        Circle circle = new Circle(116.403936, 39.915119, Metrics.KILOMETERS.getMultiplier());
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
                .newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates()
                .sortAscending()
                .limit(5);
        GeoResults results = redisTemplate.opsForGeo().radius("city", circle, args);
        System.out.println(results);

        // 通过地名查找
        Distance distance2 = new Distance(100, Metrics.KILOMETERS);
        GeoResults results2 = redisTemplate.opsForGeo().radius("city", "长城", distance2, args);
        System.out.println(results2);
    }


}

你可能感兴趣的:(Redis,redis,数据库,缓存)