ZiggyCreatures / FusionCache

FusionCache is an easy to use, fast and robust hybrid cache with advanced resiliency features.
MIT License
1.8k stars 94 forks source link

How I can sync data between cache and Database immeditately #298

Closed Son81 closed 1 month ago

Son81 commented 1 month ago

Im using Fusion Cache, Could you please help me fix this use case, many thanks

This will not work.. use case

My code

 string strStart, strEnd = "";
 _stopwatch = new System.Diagnostics.Stopwatch();
 _stopwatch.Start();
 strStart = _stopwatch.ElapsedMilliseconds.ToString();
 bool isDb = false;
 try
 {
     List<T> results = null;
     results = _cache.GetOrSet<List<T>>(
        keyCache,
       (ctx, ct) =>
       {
           isDb = true;
           List<T> result = getMethod(param) as List<T>;

           _cache.Events.Memory.Eviction += (s, e) =>
           {
               RemoveCacheValue(keyCache);
               result = GetCacheValue<T>(keyCache) as List<T>;

               CheckLogTime.LogWrite(keyCache + " = ", strStart, strEnd, "Data in cache named " + e.Key.ToString() + "  had been expired and removed");
           };                     

           #region comment
           //if (resuls is null)
           //{
           // CACHE null FOR 5 minutes
           //ctx.Options.Duration = TimeSpan.FromMinutes(5);
           // }
           //_cache.SetAsync($"{SettingConfigCache.Prefix}" + nameCache, _vendorServices.GetVendorSummaryDataByFilter(request));
           #endregion

           _stopwatch.Stop();
           strEnd = _stopwatch.ElapsedMilliseconds.ToString();
           string info = String.Format("Get data from database {0} milliseconds and start at = {1}", _stopwatch.ElapsedMilliseconds.ToString(), DateTime.UtcNow.ToString("h:mm:ss:tt"));
           CheckLogTime.LogWrite(keyCache + " = ", strStart, strEnd, info);

           return result;
       });
     if (isDb == false)
     {
         strEnd = _stopwatch.ElapsedMilliseconds.ToString();
         CheckLogTime.LogWrite(keyCache + " = ", strStart, strEnd, "Get data from cache " + _stopwatch.Elapsed.TotalMilliseconds + " milliseconds and start at = " + DateTime.UtcNow.ToString("h:mm:ss:tt"));
     }
     return results;

thank you

jodydonetti commented 1 month ago

Hi @Son81 , I reformatted your question for readability.

Will answer in a moment, I'm reading it.

jodydonetti commented 1 month ago

This will not work.. use case

  • You have data loaded in Vendor cache at Time - T1
  • Use logged in and update data for Vendor V1 and Time - T2
  • Record for V1 saved in Database
  • record in Vendor cache for V1 should be updated in cache .
  • Cache and Store (DB data should be in sync)

I'm not sure I understand, do you want to update the database and immediately the cache?

If so you can do this:

void UpdateProduct(Product product) {
  // I DON'T KNOW WHAT DB OR ORM YOU ARE USING, THIS IS GENERIC CODE
  UpdateDatabase(product);
  // UPDATE THE CACHE
 _cache.Set("product-key", product);
}

Basically when you update the database you also immediately update the cache, there's nothing magic that will do that for you.

Regarding your code sample: inside your factory (that will run every time data is not fresh in the cache) you are adding an event listener for the eviction (this _cache.Events.Memory.Eviction += ...). This is wrong, since if you need to be notified you can register the event handler only once at the beginning, at setup time or similar.

I don't know what RemoveCacheValue and GetCacheValue do: I can imagine, but without the code I'm not sure how they do it.

If you can give me more info I can try to help more.

Son81 commented 1 month ago

Thanks for your support, let me following your idea

Regards Son


From: Jody Donetti @.> Sent: Tuesday, September 17, 2024 2:26 AM To: ZiggyCreatures/FusionCache @.> Cc: Son Pham @.>; Mention @.> Subject: Re: [ZiggyCreatures/FusionCache] How I can sync data between cache and Database immeditately (Issue #298)

External Email: This email originated from outside of the organization. Please take care when clicking links or opening attachments.

This will not work.. use case

I'm not sure I understand, do you want to update the database and immediately the cache?

If so you can do this:

void UpdateProduct(Product product) { // I DON'T KNOW WHAT DB OR ORM YOU ARE USING, THIS IS GENERIC CODE UpdateDatabase(updatedProduct); // UPDATE THE CACHE _cache.Set("product-key", product); }

Basically when you update the database you also immediately update the cache, there's nothing magic that will do that for you.

Regarding your code sample: inside your factory (that will run every time data is not fresh in the cache) you are adding an event listener for the eviction (this _cache.Events.Memory.Eviction += ...). This is wrong, since if you need to be notified you can register the event handler only once at the beginning, at setup time or similar.

I don't know what RemoveCacheValue and GetCacheValue do: I can imagine, but without the code I'm not sure how they do it.

If you can give me more info I can try to help more.

— Reply to this email directly, view it on GitHubhttps://github.com/ZiggyCreatures/FusionCache/issues/298#issuecomment-2353740066, or unsubscribehttps://github.com/notifications/unsubscribe-auth/BLBHAIS3BMZW7Y2XE46TFYLZW4WGBAVCNFSM6AAAAABNV4OEEKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGNJTG42DAMBWGY. You are receiving this because you were mentioned.Message ID: @.***>