Redis實現(xiàn)附近商鋪的項目實戰(zhàn)
一、GEO數(shù)據(jù)結構
1、入門
GEO是Geolocation的縮寫,代表地理坐標。redis3.2中加入對GEO的支持,允許存儲地理坐標信息,幫助我們根據(jù)經緯度來檢索數(shù)據(jù)。
常見命令:
- GEOADD:添加一個地理空間信息,包含:經度(longitude)、緯度(latitude)、值(member)
- GEODIST:計算指定的兩個點之間的距離并返回
- GEOHASH:將指定 member 的坐標轉為 hash 字符串形式并返回
- GEOPOS:返回指定 member 的坐標
- GEORADIUS:指定圓心、半徑,找到該圓內包含的所有 member,并按照與圓心之間的距離排序后返回。6.2 以后已廢棄
- GEOSEARCH:在指定范圍內搜索 member,并按照與指定點之間的距離排序后返回。范圍可以是圓形或矩形。6.2 新功能
- GEOSEARCHSTORE:與 GEOSEARCH 功能一致,不過可以把結果存儲到一個指定的 key。6.2 新功能
2、練習
需求
1、添加下面幾條數(shù)據(jù):
- 北京南站(116.378248 39.865275)
- 北京站(116.42803 39.903738)
- 北京西站(116.322287 39.893729)
2、計算北京西站到北京站的距離
3、搜索天安門(116.397904 39.909005)附近 10km 內的所有火車站,并按照距離升序排序

搜索10km內有哪些商鋪(搜出來的會按照距離排序)和 返回北京站的坐標

二、附加商戶搜索
1、先批量導入商戶坐標
按照商戶類型做分組,類型相同的商戶作為同一組,以 typeId 作為 key 存入同一個 GEO 集合中。

編寫測試類實現(xiàn)批量導入redis中
@SpringBootTest
class HmDianPingApplicationTests {
@Autowired
private ShopServiceImpl shopService;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void loadShopData(){
// 1、查詢店鋪信息
List<Shop> list = shopService.list();
// 2、把店鋪分組,按照 typeId 分組,typeId 一致的放到一個集合中
Map<Long, List<Shop>> map = list.stream().collect(Collectors.groupingBy(Shop::getTypeId));
// 3、分批完成寫入 Redis
for (Map.Entry<Long, List<Shop>> longListEntry : map.entrySet()) {
Long typeId = longListEntry.getKey();
List<Shop> value = longListEntry.getValue();
List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(value.size());
for (Shop shop : value) {
locations.add(new RedisGeoCommands.GeoLocation<>(
shop.getId().toString(),
new Point(shop.getX(), shop.getY())
));
}
stringRedisTemplate.opsForGeo().add(RedisConstants.SHOP_GEO_KEY + typeId, locations);
}
}
}2、實現(xiàn)附近商戶功能
SpringDataRedis 的 2.3.9 版本并不支持 Redis6.2 提供的 GEOSEARCH 命令,因此我們要把他排除掉,引入我們自己的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-data-redis</artifactId>
<groupId>org.springframework.data</groupId>
</exclusion>
<exclusion>
<artifactId>lettuce-core</artifactId>
<groupId>io.lettuce</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.1.6.RELEASE</version>
</dependency>Controller
前端不一定會傳x坐標和y坐標,可能是按照熱度等其他條件來查詢,所以x和y要required = false,表示可以沒有
@RestController
@RequestMapping("/shop")
public class ShopController {
@Resource
public IShopService shopService;
/**
* 根據(jù)商鋪類型分頁查詢商鋪信息
* @param typeId 商鋪類型
* @param current 頁碼
* @return 商鋪列表
*/
@GetMapping("/of/type")
public Result queryShopByType(
@RequestParam("typeId") Integer typeId,
@RequestParam(value = "current", defaultValue = "1") Integer current,
@RequestParam(value = "x", required = false) Double x,
@RequestParam(value = "y", required = false) Double y
) {
return shopService.queryShopByType(typeId, current, x, y);
}
}Service
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
// 判斷是否需要根據(jù)坐標查詢
if(x == null || y == null){
// 根據(jù)類型分頁查詢
Page<Shop> page = query()
.eq("type_id", typeId)
.page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
// 返回數(shù)據(jù)
return Result.ok(page.getRecords());
}
// 計算分頁參數(shù)
int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
// 查詢 Redis,按照距離排序、分頁。
GeoResults<RedisGeoCommands.GeoLocation<String>> search = stringRedisTemplate.opsForGeo().
search(RedisConstants.SHOP_GEO_KEY + typeId,
GeoReference.fromCoordinate(x, y),
new Distance(5000),
RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
if(search == null){
return Result.ok(Collections.emptyList());
}
// 查詢 Redis,按照距離排序、分頁
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = search.getContent();
if(from >= content.size()){
return Result.ok(Collections.emptyList());
}
List<Long> ids = new ArrayList<>(content.size());
Map<String, Distance> distanceMap = new HashMap<>(content.size());
// 截取 from ~ end 的部分
content.stream().skip(from).forEach(result -> {
// 獲取店鋪 id
String shopIdStr = result.getContent().getName();
ids.add(Long.valueOf(shopIdStr));
// 獲取距離
Distance distance = result.getDistance();
distanceMap.put(shopIdStr, distance);
});
String join = StrUtil.join(",", ids);
// 根據(jù) id 查詢 shop
List<Shop> shopList = query().in("id", ids).last("order by field(" + join + ")").list();
for (Shop shop : shopList) {
shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
}
return Result.ok(shopList);
}
}到此這篇關于Redis實現(xiàn)附近商鋪的項目實戰(zhàn)的文章就介紹到這了,更多相關Redis 附近商鋪內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
淺析對redis?hashtable?的sizemask理解
在?Redis?的哈希表實現(xiàn)中,index?=?hash?&?dict->ht[0].sizemask?是計算鍵值對應存儲位置的核心操作,本文給大家介紹redis?hashtable?的sizemask理解,感興趣的朋友一起看看吧2025-03-03
Redis動態(tài)熱點數(shù)據(jù)緩存策略設計
本文主要介紹了Redis動態(tài)熱點數(shù)據(jù)緩存策略設計,包括熱點數(shù)據(jù)識別、動態(tài)緩存、多級緩存、預加載機制、更新策略以及監(jiān)控告警等,具有一定的參考價值,感興趣的可以了解一下2025-01-01

