Skip to content
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

[BLOOM-138] refactor: 알림 기능 FCM -> Expo API 변경 #138

Merged
merged 3 commits into from
Oct 24, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import org.springframework.batch.core.Job
import org.springframework.batch.core.JobParameters
import org.springframework.batch.core.JobParametersBuilder
import org.springframework.batch.core.launch.JobLauncher
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import org.springframework.util.StopWatch
import java.util.concurrent.TimeUnit
Expand All @@ -14,6 +15,7 @@ class NotificationScheduler(
private val jobLauncher: JobLauncher,
private val notificationJob: Job,
) {
@Scheduled(cron = "0 0 5-23 * * *")
fun run() {
val jobParameters: JobParameters =
JobParametersBuilder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package dnd11th.blooming.batch.notification

import dnd11th.blooming.client.fcm.PushNotification
import dnd11th.blooming.client.expo.PushNotification
import dnd11th.blooming.core.entity.myplant.UserPlantDto
import org.springframework.batch.core.Job
import org.springframework.batch.core.Step
Expand All @@ -20,7 +20,7 @@ import org.springframework.transaction.PlatformTransactionManager
@Configuration
class PlantNotificationJobConfig {
companion object {
const val CHUNK_SIZE: Int = 1000
const val CHUNK_SIZE: Int = 100
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package dnd11th.blooming.batch.notification

import dnd11th.blooming.client.fcm.PushNotification
import dnd11th.blooming.client.expo.PushNotification
import dnd11th.blooming.core.entity.myplant.UserPlantDto
import org.springframework.batch.core.configuration.annotation.StepScope
import org.springframework.batch.item.ItemProcessor
Expand All @@ -13,7 +13,7 @@ class PlantNotificationProcessor {
@StepScope
fun waterNotificationItemProcessor(): ItemProcessor<UserPlantDto, PushNotification> {
return ItemProcessor { userPlantDto ->
PushNotification.create(userPlantDto.myPlantId, userPlantDto.deviceToken, userPlantDto.plantNickname)
PushNotification.create(userPlantDto.deviceToken, userPlantDto.plantNickname)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ class PlantNotificationReader(
fun waterNotificationItemReader(): ListItemReader<UserPlantDto> {
val now: LocalTime = LocalTime.now()
val alarmTime = AlarmTime.fromHour(now)

val userPlantByAlarmTime: List<UserPlantDto> =
myPlantRepository.findNeedWaterPlantsByAlarmTimeInBatch(alarmTime)
return ListItemReader(userPlantByAlarmTime)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
package dnd11th.blooming.batch.notification

import dnd11th.blooming.client.fcm.FcmService
import dnd11th.blooming.client.fcm.PushNotification
import dnd11th.blooming.client.expo.PushNotification
import dnd11th.blooming.client.expo.PushService
import dnd11th.blooming.common.util.Logger.Companion.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.springframework.batch.core.configuration.annotation.StepScope
import org.springframework.batch.item.ItemWriter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger

@Configuration
class PlantNotificationWriter(
private val fcmService: FcmService,
private val pushService: PushService,
) {
private var counter = AtomicInteger(0)
private val customDispatcher = Executors.newFixedThreadPool(3).asCoroutineDispatcher()

@Bean
@StepScope
fun waterNotificationItemWriter(): ItemWriter<PushNotification> {
return ItemWriter { pushNotifications ->
runBlocking {
pushNotifications.forEach { pushNotification ->
launch(customDispatcher) {
val currentCount = counter.incrementAndGet()
val threadName = Thread.currentThread().name
fcmService.mock(pushNotification)
log.info { "Thread: $threadName, Count: $currentCount" }
}
val scope = CoroutineScope(customDispatcher)
return ItemWriter { chunk ->
val pushNotifications = chunk.toList()
scope.launch {
try {
val threadName = Thread.currentThread().name
pushService.mock(pushNotifications)
log.info { "Thread: $threadName, Sent ${pushNotifications.size} notifications" }
} catch (e: Exception) {
log.error(e) { "${e.message}" }
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package dnd11th.blooming.client.expo

import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody

@FeignClient(name = "expoPushClient", url = "https://exp.host/--/api/v2/push/send")
interface ExpoPushClient {
@PostMapping(consumes = ["application/json"])
fun sendPushNotification(
@RequestBody request: List<PushNotification>,
): PushNotificationResponse
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package dnd11th.blooming.client.expo

import dnd11th.blooming.common.exception.ErrorType
import dnd11th.blooming.common.exception.ExternalServerException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.springframework.stereotype.Service

@Service
class ExpoPushService(
private val expoPushClient: ExpoPushClient,
) : PushService {
override suspend fun send(push: List<PushNotification>) {
val response: PushNotificationResponse =
withContext(Dispatchers.IO) {
expoPushClient.sendPushNotification(push)
}

val errorMessages: List<String> =
response.data
.filter { it.status == "error" }
.mapNotNull { it.message }

if (errorMessages.isNotEmpty()) {
throw ExternalServerException(ErrorType.PUSH_API_CALL_EXCEPTION, errorMessages.joinToString(", "))
}
}

override suspend fun mock(push: List<PushNotification>) {
try {
delay(2000L)
} catch (e: Exception) {
println("지연 처리 중 예외 발생: ${e.message}")
}
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
package dnd11th.blooming.client.fcm
package dnd11th.blooming.client.expo

data class PushNotification(
val myPlantId: Long,
val token: String,
val to: String,
val title: String,
val content: String,
) {
companion object {
fun create(
myPlantId: Long,
token: String,
plantNickname: String,
): PushNotification {
return PushNotification(
myPlantId = myPlantId,
token = token,
to = token,
title = "블루밍",
content = "${plantNickname}에 물이 필요해요",
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package dnd11th.blooming.client.expo

data class PushNotificationResponse(
val data: List<PushResponse>,
)

data class PushResponse(
val status: String,
val id: String?,
val message: String?,
val details: ErrorDetails?,
)

data class ErrorDetails(
val error: String?,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package dnd11th.blooming.client.expo

interface PushService {
suspend fun send(push: List<PushNotification>)

suspend fun mock(push: List<PushNotification>)
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ enum class ErrorType(val status: HttpStatus, var message: String, val logLevel:

// CLIENT
OPEN_API_CALL_EXCEPTION(HttpStatus.BAD_GATEWAY, "OpenAPI 호출에 실패했습니다", LogLevel.WARN),
FIREBASE_API_CALL_EXCEPTION(HttpStatus.BAD_GATEWAY, "FCM 호출에 실패했습니다", LogLevel.WARN),
PUSH_API_CALL_EXCEPTION(HttpStatus.BAD_GATEWAY, "Push Message 전송에 실패했습니다", LogLevel.WARN),

// REGION
NOT_FOUND_REGION(HttpStatus.NOT_FOUND, "존재하지 않는 지역번호입니다.", LogLevel.DEBUG),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
package dnd11th.blooming.common.exception

class ExternalServerException(errorType: ErrorType) : MyException(errorType)
class ExternalServerException(
errorType: ErrorType,
private val customMessage: String? = null,
) : MyException(errorType) {
override val message: String
get() = customMessage ?: errorType.message
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package dnd11th.blooming.common.exception

class InternalServerException(errorType: ErrorType) : MyException(errorType)
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
package dnd11th.blooming.common.exception

abstract class MyException(val errorType: ErrorType) : RuntimeException(errorType.message)
abstract class MyException(
val errorType: ErrorType,
) : RuntimeException(errorType.message)
Loading