Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
1fb817b
Add: S2 의존성 추가
Dockerel Aug 8, 2025
75a8cfc
Add: KNU S2 geojson 파일 추가
Dockerel Aug 8, 2025
4587d1d
Feat: 애플리케이션 실행 시 KNU geojson 데이터 삭제 및 삽입
Dockerel Aug 8, 2025
facad89
feat: 현재 유저 위치 저장, 이웃 셀에 위치한 유저 조회
Dockerel Aug 11, 2025
61fe60e
feat: 초기 화면에서 인접한 요청 가져오기 위한 인접 cellId 구하는 메서드
Dockerel Aug 12, 2025
7558d35
refactor: 위치 갱신 API를 RESTful하게 리소스 기반(PUT /api/locations)으로 정리
Dockerel Aug 12, 2025
fe5534b
refactor: 레디스 파이프라인으로 조회 성능 개선
Dockerel Aug 14, 2025
3cc6931
Refactor: 현재 유저 위치 저장 로직 atomic하게 리펙터링
Dockerel Aug 14, 2025
4417548
refactor: 빌더 대신 일반 생성자 사용
Dockerel Aug 15, 2025
ac12e10
refactor: 스케줄러 응용계층과 인프라로 분리
Dockerel Aug 15, 2025
8519899
fix: isNew 판정 처리 수정
Dockerel Aug 15, 2025
6a83e0c
fix: 불필요한 Persistable 제거
Dockerel Aug 15, 2025
e3d9f2e
refactor: AuthUser 사용 및 요청 파라미터 수정
Dockerel Aug 15, 2025
89e97eb
refactor: 조회전용, 쓰기전용 모델로 분리
Dockerel Aug 16, 2025
7ffadb4
refactor: key 생성 기능 클래스로 분리
Dockerel Aug 16, 2025
fe01f30
test: 엣지 케이스들과 동시성 테스트 추가
Dockerel Aug 16, 2025
841a81a
add: @RequireAuth 어노테이션 추가
Dockerel Aug 18, 2025
baf96a8
refactor: shedlock과 redis 분산락으로 다중 인스턴스 환경 대응
Dockerel Aug 18, 2025
1c92526
refactor: OneTimeRunner 위치 변경
Dockerel Aug 18, 2025
7ee71d3
test: 활성 프로필 분리로 Redisson prod 빈 로딩 차단
Dockerel Aug 18, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ configurations {

repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}

dependencies {
Expand All @@ -41,6 +42,7 @@ dependencies {
runtimeOnly 'com.mysql:mysql-connector-j'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.session:spring-session-data-redis'
implementation 'org.redisson:redisson-spring-boot-starter:3.23.1'

// Lombok
compileOnly 'org.projectlombok:lombok'
Expand All @@ -60,10 +62,13 @@ dependencies {
implementation 'dev.langchain4j:langchain4j:1.0.0-beta1'
implementation 'dev.langchain4j:langchain4j-google-ai-gemini:1.0.0-beta1'

// S2
implementation 'com.github.google:s2-geometry-library-java:2.0.0'

// etc
implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.7.0'
implementation 'net.javacrumbs.shedlock:shedlock-spring:5.1.0'
implementation 'net.javacrumbs.shedlock:shedlock-provider-jdbc-template:5.1.0'
implementation 'net.javacrumbs.shedlock:shedlock-provider-redis-spring:5.1.0'
}

tasks.named('test') {
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/knu/ddip/common/config/RedissonConfig.java
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 src/main/java/com/knu/ddip/common/config/ScheduleConfig.java
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);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.knu.ddip.common.exception;

import com.knu.ddip.auth.exception.*;
import com.knu.ddip.location.exception.LocationNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
Expand Down Expand Up @@ -67,4 +68,12 @@ public ResponseEntity<ProblemDetail> handleTokenStolenException(TokenStolenExcep
return ResponseEntity.status(HttpStatusCode.valueOf(462)).body(problemDetail);
}

@ExceptionHandler(LocationNotFoundException.class)
public ResponseEntity<ProblemDetail> handleLocationNotFoundException(LocationNotFoundException e) {

ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
problemDetail.setTitle("Location Not Found");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problemDetail);
}

}
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);
}
}
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()
);
}
}
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);
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.knu.ddip.location.application.scheduler;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RedisTemplate, RedisConnection등과 같은 외부 시스템 의존성이 있기 때문에
스케쥴러의 특성상 운영계층보다는 인프라스트럭처 하위가 헥사고날 관점에서 좀 더 적절한 위치가 아닐까 싶네요
스케쥴러 자체 구현체를 변경할 필요까지는 없을 것 같아 포트와 어댑터를 구분할 필요까지는 없고 현재 코드대로 위치만 변경하면 괜찮을 것 같습니다

Copy link
Contributor Author

@Dockerel Dockerel Aug 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 넵 말씀하신대로 외부 시스템 의존하는 부분이 있어 인프라쪽에 더 잘 어울릴 것 같더라구요. 그래서 스케줄 실행하는 자체는 응용 계층에 두고 인프라단에 외부 의존성 관련 코드들을 옮겨 실행하도록 리펙터링하였습니다!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

의존성 코드만 옮기는 방식도 좋네요 👍


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);
}

}
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);
}
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);
}
}
}
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);
}
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";
}
}
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);
}
}
Loading
Loading