-
Notifications
You must be signed in to change notification settings - Fork 1
Feat: S2 기반 위치 관리 기능 구현 #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
1fb817b
Add: S2 의존성 추가
Dockerel 75a8cfc
Add: KNU S2 geojson 파일 추가
Dockerel 4587d1d
Feat: 애플리케이션 실행 시 KNU geojson 데이터 삭제 및 삽입
Dockerel facad89
feat: 현재 유저 위치 저장, 이웃 셀에 위치한 유저 조회
Dockerel 61fe60e
feat: 초기 화면에서 인접한 요청 가져오기 위한 인접 cellId 구하는 메서드
Dockerel 7558d35
refactor: 위치 갱신 API를 RESTful하게 리소스 기반(PUT /api/locations)으로 정리
Dockerel fe5534b
refactor: 레디스 파이프라인으로 조회 성능 개선
Dockerel 3cc6931
Refactor: 현재 유저 위치 저장 로직 atomic하게 리펙터링
Dockerel 4417548
refactor: 빌더 대신 일반 생성자 사용
Dockerel ac12e10
refactor: 스케줄러 응용계층과 인프라로 분리
Dockerel 8519899
fix: isNew 판정 처리 수정
Dockerel 6a83e0c
fix: 불필요한 Persistable 제거
Dockerel e3d9f2e
refactor: AuthUser 사용 및 요청 파라미터 수정
Dockerel 89e97eb
refactor: 조회전용, 쓰기전용 모델로 분리
Dockerel 7ffadb4
refactor: key 생성 기능 클래스로 분리
Dockerel fe01f30
test: 엣지 케이스들과 동시성 테스트 추가
Dockerel 841a81a
add: @RequireAuth 어노테이션 추가
Dockerel baf96a8
refactor: shedlock과 redis 분산락으로 다중 인스턴스 환경 대응
Dockerel 1c92526
refactor: OneTimeRunner 위치 변경
Dockerel 7ee71d3
test: 활성 프로필 분리로 Redisson prod 빈 로딩 차단
Dockerel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
src/main/java/com/knu/ddip/common/config/RedissonConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| package com.knu.ddip.common.config; | ||
|
|
||
| import org.redisson.Redisson; | ||
| import org.redisson.api.RedissonClient; | ||
| import org.redisson.config.Config; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.context.annotation.Profile; | ||
|
|
||
| @Profile("!test") | ||
| @Configuration | ||
| public class RedissonConfig { | ||
|
|
||
| @Value("${REDIS_HOST}") | ||
| private String host; | ||
|
|
||
| @Value("${REDIS_PORT}") | ||
| private int port; | ||
|
|
||
| @Value("${REDIS_PASSWORD}") | ||
| private String password; | ||
|
|
||
| @Bean | ||
| public RedissonClient redissonClient() { | ||
| Config config = new Config(); | ||
|
|
||
| config.useSingleServer() | ||
| .setAddress("redis://" + host + ":" + port) | ||
| .setPassword(password) | ||
| .setConnectionPoolSize(10) | ||
| .setConnectionMinimumIdleSize(1); | ||
|
|
||
| return Redisson.create(config); | ||
| } | ||
| } |
19 changes: 19 additions & 0 deletions
19
src/main/java/com/knu/ddip/common/config/ScheduleConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package com.knu.ddip.common.config; | ||
|
|
||
| import net.javacrumbs.shedlock.core.LockProvider; | ||
| import net.javacrumbs.shedlock.provider.redis.spring.RedisLockProvider; | ||
| import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.data.redis.connection.RedisConnectionFactory; | ||
| import org.springframework.scheduling.annotation.EnableScheduling; | ||
|
|
||
| @EnableScheduling | ||
| @Configuration | ||
| @EnableSchedulerLock(defaultLockAtLeastFor = "30s", defaultLockAtMostFor = "1m") | ||
| public class ScheduleConfig { | ||
| @Bean | ||
| public LockProvider lockProvider(RedisConnectionFactory redisConnectionFactory) { | ||
| return new RedisLockProvider(redisConnectionFactory); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 13 additions & 0 deletions
13
src/main/java/com/knu/ddip/location/application/dto/UpdateMyLocationRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package com.knu.ddip.location.application.dto; | ||
|
|
||
| import lombok.Builder; | ||
|
|
||
| @Builder | ||
| public record UpdateMyLocationRequest( | ||
| double lat, | ||
| double lng | ||
| ) { | ||
| public static UpdateMyLocationRequest of(double lat, double lng) { | ||
| return new UpdateMyLocationRequest(lat, lng); | ||
| } | ||
| } |
25 changes: 25 additions & 0 deletions
25
src/main/java/com/knu/ddip/location/application/init/GeoJsonInitializer.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| package com.knu.ddip.location.application.init; | ||
|
|
||
| import com.knu.ddip.location.application.service.LocationService; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.boot.ApplicationArguments; | ||
| import org.springframework.boot.ApplicationRunner; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class GeoJsonInitializer implements ApplicationRunner { | ||
|
|
||
| public static final String GEOJSON_INIT_LOCK_KEY = "lock:geojson:init"; | ||
|
|
||
| private final OneTimeRunner oneTimeRunner; | ||
| private final LocationService locationService; | ||
|
|
||
| @Override | ||
| public void run(ApplicationArguments args) { | ||
| oneTimeRunner.runOnce( | ||
| GEOJSON_INIT_LOCK_KEY, | ||
| () -> locationService.loadAndSaveGeoJsonFeatures() | ||
| ); | ||
| } | ||
| } |
6 changes: 6 additions & 0 deletions
6
src/main/java/com/knu/ddip/location/application/init/OneTimeRunner.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package com.knu.ddip.location.application.init; | ||
|
|
||
| public interface OneTimeRunner { | ||
| void runOnce(String lockName, Runnable task); | ||
| } | ||
|
|
26 changes: 26 additions & 0 deletions
26
src/main/java/com/knu/ddip/location/application/scheduler/LocationScheduler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package com.knu.ddip.location.application.scheduler; | ||
|
|
||
| import com.knu.ddip.location.application.service.LocationWriter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; | ||
| import org.springframework.scheduling.annotation.Scheduled; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class LocationScheduler { | ||
|
|
||
| private final LocationWriter locationWriter; | ||
|
|
||
| @SchedulerLock( | ||
| name = "cleanup_locations_lock", | ||
| lockAtLeastFor = "30s", | ||
| lockAtMostFor = "5m" | ||
| ) | ||
| @Scheduled(cron = "0 0 * * * *") // 매 정시 | ||
| public void cleanupExpiredUserLocations() { | ||
| long now = System.currentTimeMillis(); | ||
| locationWriter.cleanupExpiredUserLocations(now); | ||
| } | ||
|
|
||
| } | ||
13 changes: 13 additions & 0 deletions
13
src/main/java/com/knu/ddip/location/application/service/LocationReader.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package com.knu.ddip.location.application.service; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| public interface LocationReader { | ||
| void validateLocationByCellId(String cellId); | ||
|
|
||
| List<String> findAllLocationsByCellIdIn(List<String> cellIds); | ||
|
|
||
| List<String> findUserIdsByCellIds(List<String> targetCellIds); | ||
|
|
||
| boolean isCellIdNotInTargetArea(String cellId); | ||
| } |
135 changes: 135 additions & 0 deletions
135
src/main/java/com/knu/ddip/location/application/service/LocationService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| package com.knu.ddip.location.application.service; | ||
|
|
||
| import com.fasterxml.jackson.databind.JsonNode; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.google.common.geometry.S2CellId; | ||
| import com.knu.ddip.location.application.dto.UpdateMyLocationRequest; | ||
| import com.knu.ddip.location.application.util.S2Converter; | ||
| import com.knu.ddip.location.application.util.UuidBase64Utils; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.core.io.ClassPathResource; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.UUID; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.StreamSupport; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| @Transactional(readOnly = true) | ||
| @RequiredArgsConstructor | ||
| public class LocationService { | ||
|
|
||
| private final LocationReader locationReader; | ||
| private final LocationWriter locationWriter; | ||
|
|
||
| private final ObjectMapper objectMapper; | ||
|
|
||
| public static final int LEVEL = 17; | ||
| public static final String KNU_GEOJSON_FEATURE_FILENAME = "geojson/cells.geojson"; | ||
|
|
||
| // KNU GeoJSON 파일을 읽어서 각 Feature를 DB에 저장 | ||
| @Transactional | ||
| public void loadAndSaveGeoJsonFeatures() { | ||
| // GeoJson 파일 읽기 | ||
| String geoJsonContent = getGeoJsonContent(); | ||
|
|
||
| try { | ||
| // 기존 데이터 삭제 | ||
| locationWriter.deleteAll(); | ||
|
|
||
| // JSON 파싱 | ||
| JsonNode rootNode = objectMapper.readTree(geoJsonContent); | ||
| JsonNode featuresNode = rootNode.get("features"); | ||
| List<String> cellIds = StreamSupport.stream(featuresNode.spliterator(), false) | ||
| .map(featureNode -> featureNode.get("properties").get("id").asText()) | ||
| .collect(Collectors.toList()); | ||
|
|
||
| locationWriter.saveAll(cellIds); | ||
|
|
||
| log.info("총 {}개의 S2Cell Feature가 저장되었습니다.", cellIds.size()); | ||
| } catch (IOException e) { | ||
| e.printStackTrace(); | ||
| log.error(e.getMessage()); | ||
| } | ||
| } | ||
|
|
||
| public void saveUserLocationAtomic(UUID userId, UpdateMyLocationRequest request) { | ||
| S2CellId cellIdObj = S2Converter.toCellId(request.lat(), request.lng(), LEVEL); | ||
| String cellId = cellIdObj.toToken(); | ||
|
|
||
| // 경북대 내부에 위치하는지 확인 | ||
| boolean cellIdNotInTargetArea = locationReader.isCellIdNotInTargetArea(cellId); | ||
|
|
||
| String encodedUserId = UuidBase64Utils.uuidToBase64String(userId); | ||
|
|
||
| locationWriter.saveUserIdByCellIdAtomic(cellId, cellIdNotInTargetArea, encodedUserId); | ||
| } | ||
|
|
||
| // 요청 전송 시 이웃 userIds 조회 | ||
| public List<UUID> getNeighborRecipientUserIds(UUID myUserId, double lat, double lng) { | ||
| S2CellId cellIdObj = S2Converter.toCellId(lat, lng, LEVEL); | ||
| String cellId = cellIdObj.toToken(); | ||
|
|
||
| // 경북대 내부에 위치하는지 확인 | ||
| locationReader.validateLocationByCellId(cellId); | ||
|
|
||
| // 이웃 cellIds 가져오기 | ||
| List<S2CellId> neighbors = new ArrayList<>(); | ||
| cellIdObj.getAllNeighbors(LEVEL, neighbors); | ||
| List<String> neighborCellIds = neighbors.stream() | ||
| .map(S2CellId::toToken) | ||
| .collect(Collectors.toList()); | ||
|
|
||
| // 경북대 내부에 위치하는 이웃 cellIds만 가져오기 | ||
| List<String> targetCellIds = locationReader.findAllLocationsByCellIdIn(neighborCellIds); | ||
| targetCellIds.add(cellId); | ||
|
|
||
| // targetCellId의 userIds만 가져오기 | ||
|
|
||
| List<UUID> userIds = locationReader.findUserIdsByCellIds(targetCellIds).stream() | ||
| .map(UuidBase64Utils::base64StringToUuid) | ||
| .filter(userId -> !userId.equals(myUserId)) | ||
| .collect(Collectors.toList()); | ||
|
|
||
| return userIds; | ||
| } | ||
|
|
||
| // 초기 화면에서 인접한 요청 가져오기 (현재는 인접한 cellId 가져오는 것만 구현) | ||
| public List<String> getNeighborCellIds(double lat, double lng) { | ||
| S2CellId cellIdObj = S2Converter.toCellId(lat, lng, LEVEL); | ||
| String cellId = cellIdObj.toToken(); | ||
|
|
||
| // 경북대 내부에 위치하는지 확인 | ||
| locationReader.validateLocationByCellId(cellId); | ||
|
|
||
| // 이웃 cellIds 가져오기 | ||
| List<S2CellId> neighbors = new ArrayList<>(); | ||
| cellIdObj.getAllNeighbors(LEVEL, neighbors); | ||
| List<String> neighborCellIds = neighbors.stream() | ||
| .map(S2CellId::toToken) | ||
| .collect(Collectors.toList()); | ||
|
|
||
| // 경북대 내부에 위치하는 이웃 cellIds만 가져오기 | ||
| List<String> targetCellIds = locationReader.findAllLocationsByCellIdIn(neighborCellIds); | ||
| targetCellIds.add(cellId); | ||
|
|
||
| return targetCellIds; | ||
| } | ||
|
|
||
| private String getGeoJsonContent() { | ||
| ClassPathResource resource = new ClassPathResource(KNU_GEOJSON_FEATURE_FILENAME); | ||
| try (InputStream is = resource.getInputStream()) { | ||
| return new String(is.readAllBytes(), StandardCharsets.UTF_8); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
| } |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/knu/ddip/location/application/service/LocationWriter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package com.knu.ddip.location.application.service; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| public interface LocationWriter { | ||
| void deleteAll(); | ||
|
|
||
| void saveAll(List<String> cellIds); | ||
|
|
||
| void saveUserIdByCellIdAtomic(String newCellId, boolean cellIdNotInTargetArea, String encodedUserId); | ||
|
|
||
| void cleanupExpiredUserLocations(long now); | ||
| } |
15 changes: 15 additions & 0 deletions
15
src/main/java/com/knu/ddip/location/application/util/LocationKeyFactory.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| package com.knu.ddip.location.application.util; | ||
|
|
||
| public abstract class LocationKeyFactory { | ||
| public static String createUserIdKey(String encodedUserId) { | ||
| return "user:" + encodedUserId; | ||
| } | ||
|
|
||
| public static String createCellIdUsersKey(String cellId) { | ||
| return "cell:" + cellId + ":users"; | ||
| } | ||
|
|
||
| public static String createCellIdExpiriesKey(String cellId) { | ||
| return "cell:" + cellId + ":expiry"; | ||
| } | ||
| } |
12 changes: 12 additions & 0 deletions
12
src/main/java/com/knu/ddip/location/application/util/S2Converter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.knu.ddip.location.application.util; | ||
|
|
||
| import com.google.common.geometry.S2CellId; | ||
| import com.google.common.geometry.S2LatLng; | ||
|
|
||
| public abstract class S2Converter { | ||
|
|
||
| public static S2CellId toCellId(double lat, double lng, int level) { | ||
| S2LatLng latLng = S2LatLng.fromDegrees(lat, lng); | ||
| return S2CellId.fromLatLng(latLng).parent(level); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
RedisTemplate, RedisConnection등과 같은 외부 시스템 의존성이 있기 때문에
스케쥴러의 특성상 운영계층보다는 인프라스트럭처 하위가 헥사고날 관점에서 좀 더 적절한 위치가 아닐까 싶네요
스케쥴러 자체 구현체를 변경할 필요까지는 없을 것 같아 포트와 어댑터를 구분할 필요까지는 없고 현재 코드대로 위치만 변경하면 괜찮을 것 같습니다
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
아하 넵 말씀하신대로 외부 시스템 의존하는 부분이 있어 인프라쪽에 더 잘 어울릴 것 같더라구요. 그래서 스케줄 실행하는 자체는 응용 계층에 두고 인프라단에 외부 의존성 관련 코드들을 옮겨 실행하도록 리펙터링하였습니다!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
의존성 코드만 옮기는 방식도 좋네요 👍