Cache - v1

CSharp · Console

/Program.cs

#nullable enable
using System;
using System.Threading;
using System.Collections.Generic;

					
public class Program
{
	public static void Main()
	{
		var svc = new Services.Service();
		
		int threadCount = 30;
		
		Thread[] threads = new Thread[threadCount];

		for (int i = 0; i < threadCount; i++)
            threads[i] = new Thread((threadId) => Console.WriteLine($"Preço do produto #5 R$ {svc.GetPrice((int)threadId, 5)}, obtido na thread {threadId}"));
        
        // Iniciando as threads
        for (int i = 0; i < threadCount; i++)
        {
            threads[i].Start(i+1);
        }
				
		Console.WriteLine("Hello World ");
	}
	
	
}

namespace Services
{
	public class Service
	{
		private Infrastructure.PseudoRedis Redis = new();
		private Infrastructure.Data.ProductRepository Repository = new();
		
		public decimal? GetPrice(int threadId, int productId)
		{
		  string priceKey = $"cache:product:{productId}:price";
		  decimal? returnValue = this.Redis.Get<decimal?>(priceKey);
		  if(returnValue == null)
		  {			
			string priceLockKey = $"{priceKey}:lock";
			  
			//AQUI EU COMENTARIA ALGO COMO:
			//NÃO ALTERE, NÃO OTIMIZE, ESSA CHAMADA É INTENCIONALEMNTE REDUNDANTE
			//SE VOCÊ CONSIDERA REMOVÊ-LA, LEIA SOBRE "Double-checked locking"
			// https://en.wikipedia.org/wiki/Double-checked_locking
			  
			//using (var lockcontrol = this.Redis.Lock(key: priceLockKey, timeout: TimeSpan.FromSeconds(2), retry: 5))
			{
			  //returnValue = this.Redis.Get<decimal?>(priceKey);
			  if(returnValue == null)
			  {
				Console.WriteLine($"Cache não possui informações sobre o preço do produto {productId}, executando processamento lento na thread {threadId} ");
				returnValue = this.Repository.GetPriceByProduct(productId);
				this.Redis.Set(priceKey, returnValue);
			  }
			}
		  }
		  return returnValue;
		}
	}

}



namespace Infrastructure 
{
	public class PseudoRedis
	{
		private Dictionary<string, object> cacheMemory = new();
		private Dictionary<string, object> lockKeys = new();

		public void Set<T>(string key, T? objectToStore){
			if(objectToStore == null) return;		
			
			cacheMemory[key.ToLowerInvariant()] = objectToStore;
		}
		
		public T Get<T>(string key)
		{
			key = key.ToLowerInvariant();
			return this.cacheMemory.ContainsKey(key) ? (T)cacheMemory[key] : default;			
		}			
		
		private static object syncLoc = new Object();
		public IDisposable Lock(string key,TimeSpan timeout, int retry)
		{
			key = key.ToLowerInvariant();			
			object lockObject;
			lock(syncLoc)
			{
				if(lockKeys.ContainsKey(key))
					lockObject = lockKeys[key];
				else
				{
					lockObject = new Object();
					lockKeys[key] = lockObject;
				}
			}
			return new LockScope(key, lockObject, timeout, retry);
		}
		
	}
	
	public class LockScope : IDisposable
	{
		private readonly object _lockObject;
		private readonly bool _lockAcquired;

		public string Key { get; }
		public TimeSpan Timeout { get; }
		public int Retry { get; }

		public LockScope(string key, object lockObject, TimeSpan timeout, int retry)
		{
			_lockObject = lockObject;
			Key = key;
			Timeout = timeout;
			Retry = retry;

			_lockAcquired = TryAcquireLock();
			if (!_lockAcquired)
			{
				throw new TimeoutException($"Unable to acquire lock for key '{Key}' within the timeout period.");
			}
		}

		private bool TryAcquireLock()
		{
			for (int i = 0; i < Retry; i++)
			{
				if (Monitor.TryEnter(_lockObject, Timeout))
				{
					return true;
				}
				
				// Caso o bloqueio não seja obtido, espera antes de tentar novamente
				//Thread.Sleep(Timeout);
				Thread.Sleep(10);
			}

			return false;
		}

		public void Dispose()
		{
			if (_lockAcquired)
			{
				Monitor.Exit(_lockObject);
			}
		}
	}	
	
}

namespace Infrastructure.Data 
{
	public class ProductRepository
	{	Random rnd = new Random();
	 
		public decimal GetPriceByProduct(int productId)
		{
			decimal price = rnd.Next(1000);
			int sleep = rnd.Next(500, 1500);
			
			Console.WriteLine($"Entregando preço R$ {price}, com lentidão de {sleep}ms");
			System.Threading.Thread.Sleep(sleep);
			return price;			
		}		
	}
}
;