카테고리 없음

19주차 (1)

jaeoun0238 2025. 3. 3. 23:59

📌 NestJS + Redis Geo 기능 정리

🚀 NestJS에서 Redis의 Geo 기능을 활용한 위치 데이터 저장 및 조회


1️⃣ Redis Geo 개념

Geo 데이터란?

  • 위도(Latitude) & 경도(Longitude) 좌표를 기반으로 위치 정보를 저장 및 검색하는 기능
  • Redis는 GEOADD, GEOSEARCH 등의 명령어를 제공

Geo 데이터 저장 구조

Redis에서는 위치 데이터를 GeoSet(정렬된 Set) 형태로 저장함

Key: "bookmarksS"  
Member: "1" (북마크 ID)  
Value: (Longitude, Latitude)

2️⃣ NestJS에서 Redis Geo 기능 적용

📌 Geo 데이터 추가 (geoadd)

async geoAddBookmarkS(
  key: string,
  data: { id: number; longitude: number; latitude: number; title: string }
) {
  await this.client.geoadd(key, data.longitude, data.latitude, data.id.toString());

  // 추가 정보는 Hash로 저장
  await this.client.hset(`bookmarkS:${data.id}`, { title: data.title });
}
  • Geo 데이터 저장: geoadd() 사용하여 위치 정보 저장
  • 추가 정보 저장: hset()을 사용해 Hash에 북마크 정보 저장

📌 반경 내 북마크 검색 (geosearch)

async getNearbyBookmarksS(latitude: number, longitude: number): Promise<any[]> {
  const ids = await this.client.geosearch("bookmarksS", "FROMLONLAT", longitude, latitude, 5, "m");

  // 저장된 추가 정보 조회
  return Promise.all(ids.map(async (id) => ({
    id,
    ...(await this.client.hgetall(`bookmarkS:${id}`)),
  })));
}
  • 반경 5m 내 북마크 검색: geosearch() 사용
  • 추가 정보 조회: hgetall()을 사용해 해당 ID의 상세 정보 반환

📌 NestJS 서비스 (GeoService)

@Injectable()
export class GeoService implements OnModuleInit, OnModuleDestroy {
  private readonly client: Redis;
  constructor() { this.client = new Redis(); }

  async onModuleDestroy() { await this.client.quit(); }  // Redis 안전 종료
}
  • OnModuleDestroy에서 quit() 호출 → Redis 연결 종료 시 안정성 확보

3️⃣ 주요 개선 사항

georadius() → geosearch() 변경 (최신 Redis API 적용)
null 값 처리: hset()에서 null 대신 "" 저장
필수 값 검증 추가 (geoAddBookmarkP()에서 longitude, latitude, member 체크)