Kest

Search

Search the documentation

Microservices

Interceptors

Time, log or cache message handlers.

Interceptors wrap message handlers: logging, timing, caching, tracing. They see the pattern as the handler name and the message headers as request headers.

@Injectable
class TimingInterceptor : Interceptor {
    private val log = Logger("Messages")
    override suspend fun intercept(ctx: ExecutionContext, next: CallHandler): Any? {
        val t = System.nanoTime()
        try { return next.handle() } finally { log.log("${ctx.handler} took ${(System.nanoTime() - t) / 1_000_000} ms") }
    }
}
 
@UseInterceptors(TimingInterceptor::class) @MessagePattern("sum") fun sum(n: List<Int>) = n.sum()

To apply one to every message of the service, register it once: app.connectMicroservice(TcpOptions(4000)) { useInterceptors(TimingInterceptor::class) } (Pre-request hooks).

Good uses: a metric per pattern (count and duration, see Metrics), an audit line, a per-pattern timeout.

Read more