64 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			64 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| using System;
 | |
| using System.Collections.Generic;
 | |
| using System.Linq;
 | |
| using System.Text;
 | |
| using System.Text.RegularExpressions;
 | |
| using System.Threading.Tasks;
 | |
| 
 | |
| namespace Core.Blueprint.Redis.Helpers
 | |
| {
 | |
|     /// <summary>
 | |
|     /// Helper class for generating consistent and normalized cache keys.
 | |
|     /// </summary>
 | |
|     public static class CacheKeyHelper
 | |
|     {
 | |
|         /// <summary>
 | |
|         /// Generates a cache key based on the instance, method name, and parameters.
 | |
|         /// </summary>
 | |
|         /// <param name="instance">The instance of the class.</param>
 | |
|         /// <param name="methodName">The method name related to the cache key.</param>
 | |
|         /// <param name="parameters">The parameters used to generate the key.</param>
 | |
|         /// <returns>A normalized cache key string.</returns>
 | |
|         public static string GenerateCacheKey(object instance, string methodName, params object[] parameters)
 | |
|         {
 | |
|             var className = instance.GetType().Name;
 | |
|             var keyBuilder = new StringBuilder($"{className}.{methodName}");
 | |
| 
 | |
|             foreach (var param in parameters)
 | |
|             {
 | |
|                 string normalizedParam = NormalizeParameter(param);
 | |
|                 keyBuilder.Append($".{normalizedParam}");
 | |
|             }
 | |
| 
 | |
|             return keyBuilder.ToString();
 | |
|         }
 | |
| 
 | |
|         /// <summary>
 | |
|         /// Normalizes a parameter value for use in a cache key.
 | |
|         /// </summary>
 | |
|         /// <param name="param">The parameter to normalize.</param>
 | |
|         /// <returns>A normalized string representation of the parameter.</returns>
 | |
|         private static string NormalizeParameter(object param)
 | |
|         {
 | |
|             if (param == null)
 | |
|             {
 | |
|                 return "null";
 | |
|             }
 | |
| 
 | |
|             string paramString;
 | |
| 
 | |
|             if (param is DateTime dateTime)
 | |
|             {
 | |
|                 paramString = dateTime.ToString("yyyyMMdd");
 | |
|             }
 | |
|             else
 | |
|             {
 | |
|                 paramString = param.ToString();
 | |
|             }
 | |
| 
 | |
|             // Replace special characters with an underscore.
 | |
|             return Regex.Replace(paramString, @"[^a-zA-Z0-9]", "_");
 | |
|         }
 | |
|     }
 | |
| }
 | 
