728x90
- 파이어베이스는 2011년 파이어베이스사가 개발하고 2014년 구글에 인수된 모바일 및 웹 애플리케이션 개발 플랫폼
- 구글 드라이브와 애널리틱스를 적용해서 어떤 기기에서나 개발할 수 있는 환경을 만들어 주고, 사용자들의 이용횟수, 광고 효과, 문제 발생 빈도 등을 알려줘서 개발자들이 쉽게 활용할 수 있도록 지원
- 파이어 베이스의 인증 기능을 이용한 SSO(통합 인증)을 지원하는 서비스를 통해 사용자는 로그인을 활동을 쉽게 할 수 있음
- 파이어베이스는 NoSql 클라우드 데이터베이스에 JSON 형태로 데이터를 저장하고 클라이언트에 실시간으로 동기화
- 파이어베이스는 HTML , CSS, 자바스크립트 등과 같은 정적 콘텐츠를 빠르고 안전하게 호스팅해줍니다. 또한 SSL을 제공하기 때문에 안전하게 컨텐츠를 전송
컨트롤러단
@RestController
@RequestMapping("/push")
@Tag(name = SwaggerConstants.푸시관리, description = "푸시 관리 API")
class NotiTestController(
private val firebaseCloudMessageService: FirebaseCloudMessageService
){
@Operation(
summary = "푸시발송 테스트",
tags = [SwaggerConstants.푸시관리]
)
@PostMapping("/fcm")
fun pushMessage(@RequestBody requestDTO: RequestDTO) {
firebaseCloudMessageService.sendMessageTo(
requestDTO.targetToken,
requestDTO.title,
requestDTO.body
)
}
}
서비스단
@Component
class FirebaseCloudMessageService(private val objectMapper: ObjectMapper) {
val log = KotlinLogging.logger {}
companion object {
private val API_URL = "https://fcm.googleapis.com/v1/projects/dmpushtest3/messages:send"
private val MEDIA_TYPE_MARKDOWN = "application/json; charset=utf-8".toMediaType()
}
fun sendMessageTo(targetToken: String?, title: String?, body: String?) {
val message = makeMessage(targetToken, title, body)
val client = OkHttpClient()
val request: Request = Request.Builder()
.url(API_URL)
.post(message.toRequestBody(MEDIA_TYPE_MARKDOWN))
.addHeader(HttpHeaders.AUTHORIZATION, "Bearer $accessToken")
.addHeader(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8")
.build()
val response = client.newCall(request).execute()
log.debug { response.headers.toString() }
log.debug { response.body!!.string() }
}
fun makeMessage(targetToken: String?, title: String?, body: String?): String {
val notification = Notification(title, body, null)
val message = Message(notification, targetToken)
val fcmMessage = FcmMessageDTO(false, message)
return objectMapper.writeValueAsString(fcmMessage)
}
val accessToken: String
get() {
val firebaseConfigPath = "firebase/firebase_service_key.json"
val googleCredentials = GoogleCredentials
.fromStream(ClassPathResource(firebaseConfigPath).inputStream)
.createScoped(listOf("https://www.googleapis.com/auth/cloud-platform"))
googleCredentials.refreshIfExpired()
return googleCredentials.accessToken.tokenValue
}
}
DTO (Data Transfer Object)
class FcmMessageDTO {
var validateOnly: Boolean? = null
var message: Message? = null
constructor(validateOnly: Boolean?, message: Message?) {
this.validateOnly = validateOnly
this.message = message
}
}
class Message {
var notification:Notification? = null
var token: String? = null
constructor(notification: Notification?, token: String?) {
this.notification = notification
this.token = token
}
}
class Notification {
var title: String? = null
var body: String? = null
var image: String? = null
constructor(title: String?, body: String?, image: String?) {
this.title = title
this.body = body
this.image = image
}
}
- 위와 같이 구성을 하면 spring boot 서버에서 컨트롤러단의 api 리퀘스트를 통해 디바이스 ID(refresh token)에 해당하는 기기에 푸시 알림을 보낼 수 있었다.
- service 단에 request, response 시 FCM에서 원하는 형식으로 보내기 편리하도록 OkHttp3 라이브러리를 사용하였으며, 코틀린 관련 활용예제는 공식홈페이지(https://square.github.io/okhttp/)를 참고하여 작성하였다.
출처 : https://square.github.io/okhttp/
Overview - OkHttp
OkHttp HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. OkHttp is an HTTP client that’s efficient by default: HTTP/2 support allows all requests to
square.github.io
Firebase
Firebase is an app development platform that helps you build and grow apps and games users love. Backed by Google and trusted by millions of businesses around the world.
firebase.google.com
728x90
'Kotlin 앱 프로그래밍' 카테고리의 다른 글
(코틀린) 람다함수와 고차함수 (0) | 2023.05.28 |
---|---|
(코틀린) 데이터 클래스와 컴패니언 클래스 (2) | 2023.05.22 |
(코틀린) 상속과 오버라이딩 (0) | 2023.05.22 |
(코틀린) 주 생성자와 보조 생성자 (0) | 2023.05.22 |
코틀린 널 안정성 연산자 (0) | 2023.05.21 |