[英]How to store data in cache?
我創建了一個ViewComponent
來顯示一個List<Product>
,該列表是從REST API
服務中提取的數據,這是我的類實現:
public class ProductsViewComponent : ViewComponent
{
private readonly HttpClient _client;
public ProductsViewComponent(HttpClient client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
}
public async Task<IViewComponentResult> InvokeAsync(string date)
{
using (var response = await _client.GetAsync($"/"product/get_products/{date}"))
{
response.EnsureSuccessStatusCode();
var products = await response.Content.ReadAsAsync<List<Product>>();
return View(products);
}
}
}
我將 List 加載到Components
文件夾中可用的 html 表中: Views\\Shared\\Components\\Products\\Default.cshtml
。
在需要顯示我所做的Products
每個View
中:
@await Component.InvokeAsync("Products", new { date = myDate })
REST API
使用Startup.cs
配置的HttpClient
調用,如下所示:
services.AddHttpClient<ProductsViewComponent>(c =>
{
c.BaseAddress = new Uri('https://api.myservice.com');
});
這很有效,但主要問題是每次用戶重新加載頁面或進入另一個需要顯示產品列表的視圖時,應用程序將進行另一個API
調用。
如果日期等於之前選擇的日期,是否可以將列表存儲在緩存之類的東西中,並防止再次調用API
?
我正在學習ASP.NET Core
所以我不是這個論點的真正專家。
在此先感謝您的幫助。
根據微軟文檔https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.1
您可以使用IMemoryCache
來緩存數據
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app)
{
app.UseMvcWithDefaultRoute();
}
}
並創建IMemoryCache
實例。 這是 Microsoft 文檔中的一個示例。 您可以創建另一個類來一起處理這一切,在下面的示例中,這只是保存 DateTime 但是,您可以將任何對象保存在緩存中,當您嘗試從緩存中讀取該值時,只需將該對象轉換為類型即可。
我強烈建議您閱讀上述文檔。
public class HomeController : Controller
{
private IMemoryCache _cache;
public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
public IActionResult CacheTryGetValueSet()
{
DateTime cacheEntry;
// Look for cache key.
if (!_cache.TryGetValue(CacheKeys.Entry, out cacheEntry))
{
// Key not in cache, so get data.
cacheEntry = DateTime.Now;
// Set cache options.
var cacheEntryOptions = new MemoryCacheEntryOptions()
// Keep in cache for this time, reset time if accessed.
.SetSlidingExpiration(TimeSpan.FromSeconds(3));
// Save data in cache.
_cache.Set(CacheKeys.Entry, cacheEntry, cacheEntryOptions);
}
return View("Cache", cacheEntry);
}
}
更新: CacheKeys.Entry
是一個靜態類,其中定義了所有鍵。 (只是編碼標准)。 請檢查上面的文檔鏈接。
public static class CacheKeys
{
public static string Entry { get { return "_Entry"; } }
public static string CallbackEntry { get { return "_Callback"; } }
public static string CallbackMessage { get { return "_CallbackMessage"; } }
public static string Parent { get { return "_Parent"; } }
public static string Child { get { return "_Child"; } }
public static string DependentMessage { get { return "_DependentMessage";} }
public static string DependentCTS { get { return "_DependentCTS"; } }
public static string Ticks { get { return "_Ticks"; } }
public static string CancelMsg { get { return "_CancelMsg"; } }
public static string CancelTokenSource { get { return "_CancelTokenSource";} }
}
您可以使用分布式緩存,因此可以將 Redis 與 ConnectionMultiplexer 一起使用。 因此,foreach 調用您可以調用 redis 來獲取緩存,這要歸功於此處的接口調用 'IDistributedCache' 您可以找到很多文檔來實現緩存並使用它。 : .Net 框架
點網核心
您的控制器 X :
[HttpGet]
[Route("{itemId}")]
public async Task<IHttpActionResult> GetItemById(int eventId, [FromUri]EventTabs tabId)
{
ServiceResponse<ItemDto> result = await _itemDispatcher.GetItemById(itemId);
return WrapResponse(result);
}
您的調度員通過使用 redis 緩存的 id 獲取項目(已實現)
public class ItemDispatcher : ItemDispatcher
{
private readonly IUnitOfWork _unitOfWork;
private readonly IDistributedCache _distributedCache; // use interface of your implementation of redis cache
private readonly int _cacheDuration;
private readonly bool _isCacheEnabled;
public EventDispatcher(IUnitOfWork unitOfWork, IDistributedCache distCache)
{
_unitOfWork = unitOfWork;
_distributedCache = distCache; // init cache in constructor
_cacheDuration = _configuration.Get<int>("cache.duration"); // duration of your cache
_isCacheEnabled = _configuration.Get<bool>("cache.isEnable"); // if the cache is enable or not
}
public async Task<ServiceResponse<ItemDto>> GetItemById(int id)
{
// Add this for each Task call
var cacheKey = string.Empty;
if (_isCacheEnabled)
{
cacheKey = CacheUtils.GetCacheKey(CacheKeys.Item, id);
itemDto cacheResult = await _distributedCache.Get<ItemDto>(cacheKey);
if (cacheResult != null)
return new ServiceResponse<Item>(cacheResult);
}
}
嘗試這個
Cache["KeyName"] = VariableOrTable; Cache.Insert("Key", VariableOrTable, null,
Cache.NoAbsoluteExpiration, ts);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.