add custom prometheus metric

add tests for kafka consumer
This commit is contained in:
Denis Savosin
2024-10-08 11:41:26 +07:00
parent 377e20b871
commit 41b6d10059
11 changed files with 128 additions and 8 deletions

View File

@@ -2,6 +2,7 @@ package com.example.demo.config
import com.example.demo.services.database.city.CityService
import com.example.demo.services.kafka.Consumer
import io.micrometer.core.instrument.MeterRegistry
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.apache.kafka.common.serialization.StringDeserializer
import org.springframework.beans.factory.annotation.Autowired
@@ -18,15 +19,20 @@ class KafkaConsumerConfig(
@Bean
fun consumer(
@Autowired cityService: CityService,
): Consumer = Consumer(cityService)
@Autowired metricRegistry: MeterRegistry
): Consumer = Consumer(
cityService = cityService,
metricRegistry = metricRegistry,
)
@Bean
fun consumerFactory(): ConsumerFactory<String, String> {
val configs = mapOf(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG to kafkaProperties.bootstrapServers,
ConsumerConfig.GROUP_ID_CONFIG to kafkaProperties.consumer.groupId,
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG to kafkaProperties.consumer.autoOffsetReset,
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG to StringDeserializer::class.java,
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG to StringDeserializer::class.java,
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG to StringDeserializer::class.java
)
return DefaultKafkaConsumerFactory(configs)

View File

@@ -22,6 +22,7 @@ data class KafkaProperties @ConstructorBinding constructor(
val groupId: String,
val topics: String,
val autoStartup: Boolean,
val autoOffsetReset: String,
)
data class Validation(

View File

@@ -2,6 +2,8 @@ package com.example.demo.services.kafka
import com.example.demo.services.database.city.CityService
import com.example.demo.services.kafka.dto.CityCreateDto
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.MeterRegistry
import kotlinx.serialization.json.Json
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.messaging.handler.annotation.Payload
@@ -10,6 +12,7 @@ import org.springframework.stereotype.Component
@Component
class Consumer(
private val cityService: CityService,
private val metricRegistry: MeterRegistry,
) {
@KafkaListener(
topics = ["#{'\${kafka.consumer.topics}'.split(',')}"],
@@ -17,6 +20,13 @@ class Consumer(
)
fun handleCityCreate(@Payload message: String) {
val cityCreateDto = Json.decodeFromString<CityCreateDto>(message)
.also {
val counter = Counter.builder("kafka_consumer_city_create")
.description("consumed created city event")
.register(metricRegistry)
counter.increment()
}
cityService.create(cityCreateDto)
}
}