Redis實現(xiàn)附近商鋪的項目實戰(zhàn)
一、GEO數(shù)據(jù)結(jié)構(gòu)
1、入門
GEO是Geolocation的縮寫,代表地理坐標。redis3.2中加入對GEO的支持,允許存儲地理坐標信息,幫助我們根據(jù)經(jīng)緯度來檢索數(shù)據(jù)。
常見命令:
- GEOADD:添加一個地理空間信息,包含:經(jīng)度(longitude)、緯度(latitude)、值(member)
- GEODIST:計算指定的兩個點之間的距離并返回
- GEOHASH:將指定 member 的坐標轉(zhuǎn)為 hash 字符串形式并返回
- GEOPOS:返回指定 member 的坐標
- GEORADIUS:指定圓心、半徑,找到該圓內(nèi)包含的所有 member,并按照與圓心之間的距離排序后返回。6.2 以后已廢棄
- GEOSEARCH:在指定范圍內(nèi)搜索 member,并按照與指定點之間的距離排序后返回。范圍可以是圓形或矩形。6.2 新功能
- GEOSEARCHSTORE:與 GEOSEARCH 功能一致,不過可以把結(jié)果存儲到一個指定的 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 內(nèi)的所有火車站,并按照距離升序排序

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

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

編寫測試類實現(xiàn)批量導(dǎo)入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);
}
}到此這篇關(guān)于Redis實現(xiàn)附近商鋪的項目實戰(zhàn)的文章就介紹到這了,更多相關(guān)Redis 附近商鋪內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
redis中Could not get a resource from
這篇文章主要介紹了redis中Could not get a resource from the pool異常及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Redis 實現(xiàn)分布式鎖時需要考慮的問題解決方案
本文詳細探討了使用Redis實現(xiàn)分布式鎖時需要考慮的問題,包括鎖的競爭、鎖的釋放、超時管理、網(wǎng)絡(luò)分區(qū)等,并提供了相應(yīng)的解決方案和代碼實例,有助于開發(fā)者正確且安全地使用Redis實現(xiàn)分布式鎖2024-09-09
Linux系統(tǒng)下安裝Redis數(shù)據(jù)庫過程
大家好,本篇文章主要講的是Linux系統(tǒng)下安裝Redis數(shù)據(jù)庫過程,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12

