From d5ae9dd4450fff1450b5779ef7f1fe6dee6fc3e7 Mon Sep 17 00:00:00 2001 From: Adam Bajguz Date: Sun, 8 Oct 2023 18:03:30 +0200 Subject: [PATCH] Add caching to DefaultTypeResolver (issue #437) --- src/KafkaFlow.Serializer/DefaultTypeResolver.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/KafkaFlow.Serializer/DefaultTypeResolver.cs b/src/KafkaFlow.Serializer/DefaultTypeResolver.cs index 31cba1dff..19b6baeb2 100644 --- a/src/KafkaFlow.Serializer/DefaultTypeResolver.cs +++ b/src/KafkaFlow.Serializer/DefaultTypeResolver.cs @@ -1,18 +1,22 @@ namespace KafkaFlow { using System; + using System.Collections.Concurrent; internal class DefaultTypeResolver : IMessageTypeResolver { private const string MessageType = "Message-Type"; + private static readonly ConcurrentDictionary ConsumeTypeCache = new(StringComparer.Ordinal); + private static readonly ConcurrentDictionary ProduceTypeCache = new(); + public Type OnConsume(IMessageContext context) { var typeName = context.Headers.GetString(MessageType); return typeName is null ? - null : - Type.GetType(typeName); + null : + ConsumeTypeCache.GetOrAdd(typeName, Type.GetType); } public void OnProduce(IMessageContext context) @@ -24,9 +28,11 @@ public void OnProduce(IMessageContext context) var messageType = context.Message.Value.GetType(); - context.Headers.SetString( - MessageType, - $"{messageType.FullName}, {messageType.Assembly.GetName().Name}"); + string messageTypeName = ProduceTypeCache.GetOrAdd( + messageType, + static messageType => $"{messageType.FullName}, {messageType.Assembly.GetName().Name}"); + + context.Headers.SetString(MessageType, messageTypeName); } } }