Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
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
18 changes: 16 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,24 @@ services:
- rabbitmq_data:/var/lib/rabbitmq
restart: unless-stopped
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "check_port_connectivity"]
test: [ "CMD", "rabbitmq-diagnostics", "check_port_connectivity" ]
interval: 30s
timeout: 10s
retries: 3
mysql:
image: mysql:8.0
container_name: tracky-db
restart: always
environment:
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
MYSQL_DATABASE: ${DB_NAME}
MYSQL_USER: ${DB_USER}
MYSQL_PASSWORD: ${DB_PASSWORD}
ports:
- "3307:3306"
volumes:
- mysql_data:/var/lib/mysql

volumes:
rabbitmq_data:
rabbitmq_data:
mysql_data:
4 changes: 2 additions & 2 deletions tracky-core/src/main/resources/application-common.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ spring:

sql:
init:
mode: never
mode: always
encoding: UTF-8
schema-locations: classpath:schema.sql
data-locations: classpath:data.sql
Expand All @@ -39,7 +39,7 @@ management:
exposure:
include:
- "*"

logging:
level:
# RabbitMQ ConnectionFactory INFO 로그 끄기
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
import org.springframework.context.annotation.Configuration;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class RabbitMQConfig {
Expand All @@ -32,6 +34,7 @@ public FanoutExchange fanoutExchange() {

@Bean
public Queue gpsQueue() {
log.info("Queue 생성: gpsQueue");
return QueueBuilder.durable(properties.getQueue().getGps())
.withArgument("x-dead-letter-exchange", properties.getExchange().getDlx())
.withArgument("x-dead-letter-routing-key", properties.getRouting().getDeadLetterKey())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
Expand All @@ -19,6 +20,7 @@

@Slf4j
@Component
@Order(1)
public class HttpLoggingFilter implements Filter {
@Override
public void doFilter(
Expand All @@ -29,6 +31,11 @@ public void doFilter(
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;

if (isSseRequest(httpRequest)) {
chain.doFilter(request, response);
return;
}

ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(httpRequest);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(httpResponse);

Expand Down Expand Up @@ -89,5 +96,9 @@ private String getHeaders(HttpServletResponse response) {

return headerString.toString();
}
}

private boolean isSseRequest(HttpServletRequest request) {
String accept = request.getHeader("Accept");
return accept != null && accept.contains("text/event-stream");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ public Map<Long, Integer> countDailyTotalOperation(LocalDate targetDate) {
return OperationTotalCount.toMap(driveDomainRepository.getDailyTotalOperation(targetDate));
}

public Long findActiveDriveIdByMdn(String mdn) {
return driveDomainRepository.findRunningDriveIdByMdn(mdn)
.orElseThrow(() -> GlobalException.throwError(ErrorCode.NOT_REALTIME_DRIVE));
}

//월별 통계 - 미운행 차량 수
public Map<Long, Integer> getNonOperatedCars(LocalDate targetDate) {
return NonOperatedCar.toMap(driveDomainRepository.getNonOperatedCars(targetDate));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Page<DriveEntity> findRunningDriveListAdmin(

Optional<DriveHistory> findByDriveId(Long driveId);

Optional<Long> findRunningDriveIdByMdn(String mdn);

List<OperationCarCount> getDailyOperationCar(LocalDate targetDate);

List<OperationTotalCount> getDailyTotalOperation(LocalDate targetDate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
@Repository
@RequiredArgsConstructor
@Slf4j
public class DriveDomainRepositoryImpl implements DriveDomainRepositoryCustom {
public class DriveDomainRepositoryCustomImpl implements DriveDomainRepositoryCustom {

private final JPAQueryFactory queryFactory;

Expand Down Expand Up @@ -208,6 +208,7 @@ public Optional<DriveHistory> findByDriveId(Long driveId) {
return Optional.of(driveHistory);
}

//일일 통계 - target Date에 운행한 차량 수
@Override
public List<OperationCarCount> getDailyOperationCar(LocalDate targetDate) {
LocalDateTime start = targetDate.atStartOfDay();
Expand Down Expand Up @@ -308,6 +309,20 @@ private long fetchTotalCount(BooleanBuilder condition) {
).orElse(0L);
}

@Override
public Optional<Long> findRunningDriveIdByMdn(String mdn) {
return Optional.ofNullable(
queryFactory
.select(driveEntity.id)
.from(driveEntity)
.where(
driveEntity.car.mdn.eq(mdn),
driveEntity.driveOffTime.isNull()
)
.fetchOne()
);
}

//검색 조건
private BooleanExpression isEqualMdnContainsRenterName(String mdn, String search) {
if (StringUtils.isBlank(search)) {
Expand All @@ -326,3 +341,4 @@ private BooleanExpression isContainsBizName(String bizSearch) {
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import kernel360.trackycore.core.domain.entity.GpsHistoryEntity;
import kernel360.trackycore.core.infrastructure.repository.GpsHistoryRepository;

public interface GpsHistoryDomainRepository extends JpaRepository<GpsHistoryEntity, Long> {
public interface GpsHistoryDomainRepository extends GpsHistoryRepository {

@Query(value = """
SELECT * FROM gpshistory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,55 +13,79 @@
@Slf4j
@Service
public class EventEmitterService {
private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
private static final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
Copy link
Collaborator

Choose a reason for hiding this comment

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

static으로 두신 이유가 있나요?


public static Map<String, SseEmitter> getTest() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

사용하지 않는 함수같은데 지우는게 좋을 것 같습니다

return emitters;
}

public SseEmitter subscribe(String driveId) {

SseEmitter oldEmitter = emitters.get(driveId);
if (oldEmitter != null) {
oldEmitter.complete(); // 연결 종료
emitters.remove(driveId);
log.info("기존 SSE 연결 종료: driveId = {}", driveId);
}

public SseEmitter subscribe(String clientId) {
SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
emitters.put(clientId, emitter);

log.info("SSE 구독 연결: clientId = {}", clientId);
emitters.put(driveId, emitter);

emitter.onCompletion(() -> emitters.remove(clientId));
emitter.onTimeout(() -> emitters.remove(clientId));
emitter.onError((e) -> emitters.remove(clientId));
log.info("SSE 연결: driveId = {}, emitter={}", driveId, emitter);

emitter.onCompletion(() -> {
log.info("SSE 연결 종료: driveId = {}", driveId);
emitters.remove(driveId);
});

emitter.onTimeout(() -> emitters.remove(driveId));
emitter.onError((e) -> emitters.remove(driveId));

try {
emitter.send(SseEmitter.event().comment("connected"));

emitter.send(SseEmitter.event()
.name("init")
.data("SSE 연결 성공"));
} catch (Exception e) {
log.error("초기 SSE 메시지 전송 실패: clientId = {}", clientId, e);
log.error("초기 SSE 메시지 전송 실패: driveId = {}", driveId, e);
emitter.completeWithError(e);
emitters.remove(clientId);
emitters.remove(driveId);
}

return emitter;
}

public void sendEvent(String eventName, Object data) {
emitters.forEach((key, emitter) -> {
try {
emitter.send(SseEmitter.event()
.name(eventName)
.data(data));
} catch (IOException e) {
log.warn("SSE 연결 실패 (eventName: {}): {}", eventName, e.getMessage());
emitter.completeWithError(e);
emitters.remove(key);
}
});
public void sendToDriveId(String driveId, String eventName, Object data) {
SseEmitter emitter = emitters.get(driveId);
log.info("emitters.get({}) 결과: {}", driveId, emitter);

if (emitter == null) {
log.warn("SSE 전송 실패: driveId={}, event={}", driveId, eventName);
return;
}

try {
emitter.send(SseEmitter.event().name(eventName).data(data));
log.info("emitter.send 성공");
} catch (Exception e) {
log.error("emitter.send 실패: {}", e.getMessage(), e);
emitter.completeWithError(e);
emitters.remove(driveId);
}
}

// keep-alive 메시지를 15초마다 전송
@Scheduled(fixedRate = 15000)
public void sendKeepAlive() {
emitters.forEach((clientId, emitter) -> {
emitters.forEach((driveId, emitter) -> {
try {
emitter.send(SseEmitter.event().comment("keep-alive"));
} catch (IOException e) {
log.warn("SSE keep-alive 실패: clientId = {}", clientId);
log.warn("SSE keep-alive 실패: driveId = {}", driveId);
emitter.completeWithError(e);
emitters.remove(clientId);
emitters.remove(driveId);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package kernel360.trackyweb.emitter;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequiredArgsConstructor
Expand All @@ -15,9 +18,8 @@ public class EventSseController {

private final EventEmitterService eventEmitterService;

@GetMapping("/subscribe")
public SseEmitter subscribe(@RequestParam String clientId) {
return eventEmitterService.subscribe(clientId);
@GetMapping(value = "/subscribe", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter subscribe(@RequestParam String driveId) {
return eventEmitterService.subscribe(driveId);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package kernel360.trackyweb.emitter;

import kernel360.trackyweb.realtime.application.dto.request.CycleGpsRequest;

public record GpsPointResponse(
double lat,
double lon,
int ang,
int spd,
String oTime,
double sum
) {
public static GpsPointResponse from(CycleGpsRequest req) {
return new GpsPointResponse(
req.gpsInfo().getLat(),
req.gpsInfo().getLon(),
req.gpsInfo().getAng(),
req.gpsInfo().getSpd(),
req.oTime().toString(),
req.gpsInfo().getSum()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,17 @@
import kernel360.trackyweb.realtime.application.dto.response.GpsDataResponse;
import kernel360.trackyweb.realtime.application.dto.response.RunningCarDetailResponse;
import kernel360.trackyweb.realtime.application.dto.response.RunningCarResponse;
// import kernel360.trackyweb.realtime.domain.provider.GpsHistoryDomainProvider;
import kernel360.trackyweb.realtime.domain.provider.GpsHistoryDomainProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@RequiredArgsConstructor

@Slf4j
public class RealTimeService {

private final DriveDomainProvider driveDomainProvider;
// private final GpsHistoryDomainProvider gpsHistoryDomainProvider;
private final GpsHistoryDomainProvider gpsHistoryDomainProvider;

@Transactional(readOnly = true)
public ApiResponse<List<RunningCarResponse>> getRunningCars(
Expand Down Expand Up @@ -52,15 +53,13 @@ public ApiResponse<RunningCarDetailResponse> getRunningCarDetailById(Long id) {
return ApiResponse.success(RunningCarDetailResponse.from(drive, sum));
}

// @Transactional(readOnly = true)
// public GpsDataResponse getOneGps(Long id) {
// return gpsHistoryDomainProvider.getOneGpsByDriveId(id);
// }
//
// public List<GpsDataResponse> getNowGpsPath(Long id, LocalDateTime nowTime) {
// return gpsHistoryDomainProvider.getGpsListAfterTime(id, nowTime).stream()
// .map(GpsDataResponse::from)
// .toList();
// }
@Transactional(readOnly = true)
public List<GpsDataResponse> getBeforeGpsPath(Long id, LocalDateTime nowTime) {
log.info("nowTime{}", nowTime);
return gpsHistoryDomainProvider.getGpsPathBeforeTime(id, nowTime)
.stream()
.map(GpsDataResponse::from)
.toList();
}

}
Loading