Skip to content

Instantly share code, notes, and snippets.

@tuannguyenssu
Created September 26, 2019 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuannguyenssu/28f3361d34630964e4b2fab432228f26 to your computer and use it in GitHub Desktop.
Save tuannguyenssu/28f3361d34630964e4b2fab432228f26 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Caching.Distributed;
using System.Text;
namespace RedisTest.Controllers
{
[Route("api/[controller]")]
public class RedisController : Controller
{
private readonly IDistributedCache _distributedCache;
public RedisController(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
[HttpGet]
public string Get()
{
var cacheKey = "TheTime";
var currentTime = DateTime.Now.ToString();
var cachedTime = _distributedCache.GetString(cacheKey);
if(string.IsNullOrEmpty(cachedTime))
{
// cachedTime = "Expired";
// Cache expire trong 5s
var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(5));
// Nạp lại giá trị mới cho cache
_distributedCache.SetString(cacheKey, currentTime, options);
cachedTime = _distributedCache.GetString(cacheKey);
}
var result = $"Current Time : {currentTime} \nCached Time : {cachedTime}";
return result;
}
}
}
@Bathe0603it
Copy link

Bathe0603it commented Oct 28, 2021

copied

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment