Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,6 @@ out/

.env

src/main/resources/application.yml
src/main/resources/application.yml
src/main/resources/application-local.yml
src/main/resources/application-prod.yml
10 changes: 10 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ dependencies {

// Discord
implementation (Dependency.Discord.WEB_HOOK)

// Actuator
implementation (Dependency.Spring.ACTUATOR)

// Prometheus
implementation (Dependency.Spring.PROMETHEUS)
}

kotlin {
Expand Down Expand Up @@ -117,3 +123,7 @@ tasks.bootJar {
into("static/docs")
}
}

springBoot {
buildInfo()
}
2 changes: 2 additions & 0 deletions buildSrc/src/main/kotlin/Dependency.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ object Dependency {
val BOOT_STARTER_ACTUATOR = starter("-actuator")
val SPRINGDOC = "org.springdoc:springdoc-openapi-starter-webmvc-ui:$SPRINGDOC_VERSION"
val RESTDOCS_MOCKMVC = "org.springframework.restdocs:spring-restdocs-mockmvc:$RESTDOCS_MOCKMVC_VERSION"
val ACTUATOR = "$BASE:spring-boot-starter-actuator"
val PROMETHEUS = "io.micrometer:micrometer-registry-prometheus"
}

object Kotlin {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.coffee.api.cafe.application
import com.coffee.api.cafe.application.port.inbound.FindCafe
import com.coffee.api.cafe.application.port.outbound.CafeRepository
import com.coffee.api.cafe.domain.CafeArea
import io.micrometer.core.annotation.Counted
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

Expand All @@ -12,6 +13,7 @@ class CafeService(
private val cafeRepository: CafeRepository,
) : FindCafe {

@Counted(value = "cafe.find", description = "Number of times cafe list is requested")
override fun invoke(query: FindCafe.Query): FindCafe.Result {
val area = query.area?.let { code ->
CafeArea.entries.find { it.name == code }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.coffee.api.cafe.presentation.adapter.`in`.restapi.dto.response.*
import com.coffee.api.cafe.presentation.adapter.`in`.restapi.mapper.FindAllCafesResponseMapper
import com.coffee.api.cafe.presentation.adapter.`in`.restapi.mapper.GetCafeDetailsResponseMapper
import com.coffee.api.cafe.presentation.docs.CafeApi
import com.coffee.api.common.aop.PageViewed
import com.coffee.api.common.support.response.ApiResponse
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
Expand All @@ -25,6 +26,7 @@ class CafeController(
val findRecommendCafe: FindRecommendCafe,
) : CafeApi {

@PageViewed("cafe_list")
@GetMapping
override fun findAllCafes(
@RequestParam(value = "lastCafeId", required = false) lastCafeId: UUID?,
Expand All @@ -35,6 +37,7 @@ class CafeController(
return ApiResponse.success(response)
}

@PageViewed("cafe_details")
@GetMapping("/details/{cafeId}")
override fun getCafeDetails(
@PathVariable cafeId: UUID,
Expand All @@ -44,12 +47,14 @@ class CafeController(
return ApiResponse.success(response)
}

@PageViewed("areas")
@GetMapping("/areas")
override fun getAreas(): ApiResponse<FindCafeArea.Result> {
val response = findCafeArea.execute(Unit)
return ApiResponse.success(response)
}

@PageViewed("cafe_recommend")
@GetMapping("/recommend")
override fun getRecommendCafes(lastGroupId: UUID?, limit: Int): ApiResponse<FindRecommendCafe.Result> {
return ApiResponse.success(findRecommendCafe.execute(FindRecommendCafe.Query(lastGroupId, limit)))
Expand Down
24 changes: 24 additions & 0 deletions src/main/kotlin/com/coffee/api/common/aop/PageViewAspect.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.coffee.api.common.aop

import io.micrometer.core.instrument.MeterRegistry
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.springframework.stereotype.Component

@Aspect
@Component
class PageViewAspect(
private val meterRegistry: MeterRegistry
) {

@Before("@annotation(pageViewed)")
fun countPageView(joinPoint: JoinPoint, pageViewed: PageViewed) {
val counterName = "page.view.count"
val tagName = pageViewed.name

meterRegistry
.counter(counterName, "page", tagName)
.increment()
}
}
Comment on lines +1 to +24

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

페이지 뷰 측정을 위한 AOP 구현

페이지 뷰 메트릭을 수집하기 위한 AOP 클래스를 구현했습니다. @PageViewed 애노테이션이 적용된 메서드 실행 전에 메트릭을 증가시키는 방식으로 구현되었습니다.

하지만 몇 가지 개선할 점이 있습니다:

  1. 에러 처리 코드가 없어 메트릭 등록 중 오류가 발생해도 이를 처리하는 방법이 없습니다.
  2. "page.view.count"라는 카운터 이름이 하드코딩되어 있어 향후 변경이 필요할 경우 코드 수정이 필요합니다.
 package com.coffee.api.common.aop

 import io.micrometer.core.instrument.MeterRegistry
 import org.aspectj.lang.JoinPoint
 import org.aspectj.lang.annotation.Aspect
 import org.aspectj.lang.annotation.Before
+import org.slf4j.LoggerFactory
 import org.springframework.stereotype.Component

 @Aspect
 @Component
 class PageViewAspect(
-    private val meterRegistry: MeterRegistry
+    private val meterRegistry: MeterRegistry,
+    private val counterName: String = "page.view.count"
 ) {
+    private val logger = LoggerFactory.getLogger(javaClass)

     @Before("@annotation(pageViewed)")
     fun countPageView(joinPoint: JoinPoint, pageViewed: PageViewed) {
-        val counterName = "page.view.count"
         val tagName = pageViewed.name

-        meterRegistry
-            .counter(counterName, "page", tagName)
-            .increment()
+        try {
+            meterRegistry
+                .counter(counterName, "page", tagName)
+                .increment()
+        } catch (e: Exception) {
+            logger.error("페이지 뷰 메트릭 증가 중 오류 발생: {}", e.message, e)
+        }
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
package com.coffee.api.common.aop
import io.micrometer.core.instrument.MeterRegistry
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.springframework.stereotype.Component
@Aspect
@Component
class PageViewAspect(
private val meterRegistry: MeterRegistry
) {
@Before("@annotation(pageViewed)")
fun countPageView(joinPoint: JoinPoint, pageViewed: PageViewed) {
val counterName = "page.view.count"
val tagName = pageViewed.name
meterRegistry
.counter(counterName, "page", tagName)
.increment()
}
}
package com.coffee.api.common.aop
import io.micrometer.core.instrument.MeterRegistry
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
@Aspect
@Component
class PageViewAspect(
private val meterRegistry: MeterRegistry,
private val counterName: String = "page.view.count"
) {
private val logger = LoggerFactory.getLogger(javaClass)
@Before("@annotation(pageViewed)")
fun countPageView(joinPoint: JoinPoint, pageViewed: PageViewed) {
val tagName = pageViewed.name
try {
meterRegistry
.counter(counterName, "page", tagName)
.increment()
} catch (e: Exception) {
logger.error("페이지 뷰 메트릭 증가 중 오류 발생: {}", e.message, e)
}
}
}

5 changes: 5 additions & 0 deletions src/main/kotlin/com/coffee/api/common/aop/PageViewed.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.coffee.api.common.aop

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class PageViewed(val name: String)
4 changes: 3 additions & 1 deletion src/main/kotlin/com/coffee/api/config/ApiControllerAdvice.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

@RestControllerAdvice
@RestControllerAdvice(
basePackages = ["com.coffee.api.cafe.presentation.adapter.in.restapi"]
)
@io.swagger.v3.oas.annotations.Hidden
class ApiControllerAdvice(
private val discordClientAdapter: DiscordClientAdapter
Expand Down
14 changes: 14 additions & 0 deletions src/main/kotlin/com/coffee/api/config/aop/CafeConfig.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.coffee.api.config.aop

import io.micrometer.core.aop.CountedAspect
import io.micrometer.core.instrument.MeterRegistry
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class CafeConfig {

@Bean
fun countedAspect(registry: MeterRegistry): CountedAspect =
CountedAspect(registry)
}