1655811600
Chúng ta sẽ thảo luận về bộ nhớ đệm trong .NET Core và cách thức hoạt động của nó. Vì vậy, chúng ta xem xét từng thứ sau đây.
Vì vậy, chúng ta hãy bắt đầu từng cái một.
Bộ nhớ đệm ngày nay rất phổ biến trong ngành công nghiệp phần mềm vì nó sẽ cải thiện hiệu suất và khả năng mở rộng của ứng dụng, khi chúng tôi sử dụng và thấy nhiều ứng dụng web như G-mail và Facebook cũng như mức độ phản hồi của chúng và trải nghiệm người dùng tuyệt vời khi chúng tôi sử dụng ứng dụng đó. Có rất nhiều người dùng sử dụng Internet và nếu một ứng dụng có lưu lượng và nhu cầu mạng lớn và do đó chúng ta cần quan tâm đến nhiều thứ để giúp chúng ta cải thiện hiệu suất và khả năng phản hồi của ứng dụng. Vì vậy, do đó, có một trong những giải pháp là bộ nhớ đệm và đó là lý do bộ nhớ đệm xuất hiện trong bức tranh.
Bộ nhớ đệm là bộ nhớ lưu trữ được sử dụng để lưu trữ dữ liệu truy cập thường xuyên vào bộ lưu trữ tạm thời, nó sẽ cải thiện hiệu suất đáng kể và tránh bị tấn công cơ sở dữ liệu không cần thiết và lưu trữ dữ liệu thường xuyên sử dụng vào bộ đệm bất cứ khi nào chúng ta cần.
Như bạn thấy trong hình trên, có hai tình huống một là không sử dụng bộ đệm và một là với bộ đệm và cách nó hoạt động. Vì vậy, ở đây khi chúng ta không sử dụng bộ nhớ cache, trong trường hợp đó, giả sử người dùng muốn có dữ liệu thì họ sẽ đánh mỗi lần cơ sở dữ liệu và nó sẽ làm tăng thời gian phức tạp và giảm hiệu suất. Trong trường hợp có một số dữ liệu tĩnh người dùng muốn và nó giống nhau cho tất cả người dùng, trong trường hợp đó khi chúng ta không sử dụng bộ nhớ cache thì mỗi người đánh vào cơ sở dữ liệu không cần thiết để tìm nạp dữ liệu. Và ở mặt khác, như bạn có thể thấy nếu chúng tôi sử dụng bộ nhớ cache và trong trường hợp đó, nếu có cùng một dữ liệu tĩnh và giống nhau cho tất cả người dùng thì chỉ người dùng đầu tiên sẽ truy cập cơ sở dữ liệu và tìm nạp dữ liệu và lưu trữ vào bộ nhớ đệm, sau đó khác hai người dùng sử dụng nó từ bộ nhớ cache mà không cần nhấn vào cơ sở dữ liệu để tìm nạp dữ liệu một cách không cần thiết.
Về cơ bản, có hai loại bộ nhớ đệm .NET Core hỗ trợ
Khi chúng tôi sử dụng In-Memory Cache thì trong trường hợp đó, dữ liệu được lưu trữ trong bộ nhớ của máy chủ ứng dụng và bất cứ khi nào chúng tôi cần thì chúng tôi tìm nạp dữ liệu từ đó và sử dụng nó ở bất cứ đâu chúng tôi cần. Và trong Bộ đệm ẩn phân tán có nhiều cơ chế của bên thứ ba như Redis và nhiều cơ chế khác. Nhưng trong phần này, chúng tôi xem xét chi tiết Bộ nhớ đệm trong bộ nhớ và cách nó hoạt động trong .NET Core.
Về cơ bản, In-Memory Cache được sử dụng cho các ứng dụng nhẹ và nhỏ và sẽ hoạt động tốt trong đó. Nó lưu trữ dữ liệu vào bộ nhớ máy chủ ở phía ứng dụng và người dùng sử dụng nó bất cứ khi nào có nhu cầu.
Ưu điểm của bộ nhớ đệm trong bộ nhớ
Nhược điểm của bộ nhớ đệm trong bộ nhớ
Bây giờ chúng ta sẽ tạo một .NET Core API, triển khai bộ nhớ đệm vào đó và hiểu mọi thứ sẽ hoạt động như thế nào.
Bước 1
Tạo ứng dụng web .NET Core API
Bước 2
Cài đặt các Gói NuGet sau đây cần từng bước trong ứng dụng của chúng tôi
Bước 3
Tạo thư mục Model và tạo một Lớp Sản phẩm bên trong với các chi tiết
namespace MemoryCacheDemo.Model
{
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public int Stock { get; set; }
}
}
Bước 4
Tiếp theo, Tạo Lớp DbContextClass cho các hoạt động liên quan đến Cơ sở dữ liệu như tôi đã trình bày bên dưới
using MemoryCacheDemo.Model;
using Microsoft.EntityFrameworkCore;
namespace MemoryCacheDemo.Data {
public class DbContextClass: DbContext {
public DbContextClass(DbContextOptions < DbContextClass > options): base(options) {}
public DbSet < Product > Products {
get;
set;
}
}
}
Bước 5
Bây giờ, chúng ta sẽ tạo Giao diện ICacheService và Lớp CacheService để sử dụng liên quan đến Bộ nhớ cache trong bộ nhớ.
using System;
using System.Collections.Generic;
namespace MemoryCacheDemo.Cache
{
public interface ICacheService
{
/// <summary>
/// Get Data using key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
T GetData<T>(string key);
/// <summary>
/// Set Data with Value and Expiration Time of Key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
bool SetData<T>(string key, T value, DateTimeOffset expirationTime);
/// <summary>
/// Remove Data
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
object RemoveData(string key);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
namespace MemoryCacheDemo.Cache {
public class CacheService: ICacheService {
ObjectCache _memoryCache = MemoryCache.Default;
public T GetData < T > (string key) {
try {
T item = (T) _memoryCache.Get(key);
return item;
} catch (Exception e) {
throw;
}
}
public bool SetData < T > (string key, T value, DateTimeOffset expirationTime) {
bool res = true;
try {
if (!string.IsNullOrEmpty(key)) {
_memoryCache.Set(key, value, expirationTime);
}
} catch (Exception e) {
throw;
}
return res;
}
public object RemoveData(string key) {
try {
if (!string.IsNullOrEmpty(key)) {
return _memoryCache.Remove(key);
}
} catch (Exception e) {
throw;
}
return false;
}
}
}
Bước 6
Tạo lớp ProductController, tạo phương thức sau như hình bên dưới
using MemoryCacheDemo.Cache;
using MemoryCacheDemo.Data;
using MemoryCacheDemo.Model;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MemoryCacheDemo.Controllers {
[Route("api/[controller]")]
[ApiController]
public class ProductController: ControllerBase {
private readonly DbContextClass _dbContext;
private readonly ICacheService _cacheService;
public ProductController(DbContextClass dbContext, ICacheService cacheService) {
_dbContext = dbContext;
_cacheService = cacheService;
}
[HttpGet("products")]
public IEnumerable < Product > Get() {
var cacheData = _cacheService.GetData < IEnumerable < Product >> ("product");
if (cacheData != null) {
return cacheData;
}
var expirationTime = DateTimeOffset.Now.AddMinutes(5.0);
cacheData = _dbContext.Products.ToList();
_cacheService.SetData < IEnumerable < Product >> ("product", cacheData, expirationTime);
return cacheData;
}
[HttpGet("product")]
public Product Get(int id) {
Product filteredData;
var cacheData = _cacheService.GetData < IEnumerable < Product >> ("product");
if (cacheData != null) {
filteredData = cacheData.Where(x => x.ProductId == id).FirstOrDefault();
return filteredData;
}
filteredData = _dbContext.Products.Where(x => x.ProductId == id).FirstOrDefault();
return filteredData;
}
[HttpPost("addproduct")]
public async Task < Product > Post(Product value) {
var obj = await _dbContext.Products.AddAsync(value);
_cacheService.RemoveData("product");
_dbContext.SaveChanges();
return obj.Entity;
}
[HttpPut("updateproduct")]
public void Put(Product product) {
_dbContext.Products.Update(product);
_cacheService.RemoveData("product");
_dbContext.SaveChanges();
}
[HttpDelete("deleteproduct")]
public void Delete(int Id) {
var filteredData = _dbContext.Products.Where(x => x.ProductId == Id).FirstOrDefault();
_dbContext.Remove(filteredData);
_cacheService.RemoveData("product");
_dbContext.SaveChanges();
}
}
}
Bước 7
Thêm chuỗi kết nối SQL Server bên trong appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=server;Initial Catalog=MemoryCache;User Id=****;Password=***;"
}
}
Bước 8
Tiếp theo, Đăng ký ICacheService bên trong phương thức Cấu hình Dịch vụ của Lớp Khởi động và cũng thêm một số cấu hình liên quan đến Swagger để kiểm tra các điểm cuối API của chúng tôi
using MemoryCacheDemo.Cache;
using MemoryCacheDemo.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
namespace MemoryCacheDemo {
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration {
get;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
services.AddScoped < ICacheService, CacheService > ();
services.AddDbContext < DbContextClass > (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo {
Title = "MemoryCacheDemo", Version = "v1"
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MemoryCacheDemo v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
}
}
Bước 9
Thực hiện Di chuyển và Cập nhật Cơ sở dữ liệu cho Tạo DB bằng các lệnh sau trong Bảng điều khiển Trình quản lý Gói.
add -igration “FirstMigration”
cập nhật cơ sở dữ liệu
Vì vậy, khi bạn nhập và thực thi lệnh này, nó sẽ tạo ra một số thứ liên quan đến việc di chuyển và tạo cơ sở dữ liệu bên trong SQL Server khi bạn đặt bên trong Chuỗi kết nối trong appsetting.json
Bước 10
Cuối cùng, chạy ứng dụng và thêm dữ liệu bằng giao diện người dùng swagger và sau đó kiểm tra cách bộ nhớ đệm hoạt động bên trong sản phẩm và điểm cuối của sản phẩm.
Về cơ bản, tôi đã thêm bộ nhớ cache vào sản phẩm và các điểm cuối của sản phẩm trong bộ điều khiển, như bạn thấy khi người dùng muốn tìm nạp dữ liệu của tất cả các sản phẩm thì trước tiên, nó sẽ kiểm tra xem dữ liệu có bên trong Bộ nhớ đệm trong bộ nhớ hay không và nếu nó có mặt bên trong bộ đệm, sau đó trả lại dữ liệu đó cho người dùng và nếu dữ liệu không có bên trong bộ đệm, thì nó sẽ tìm nạp dữ liệu từ cơ sở dữ liệu và cũng có thể đặt dữ liệu đó vào bộ đệm. Vì vậy, lần sau người dùng sẽ chỉ nhận được điều đó từ bộ nhớ cache và tránh đánh vào cơ sở dữ liệu một cách không cần thiết
Ngoài ra, khi người dùng muốn tìm nạp dữ liệu bằng cách sử dụng id sản phẩm như bạn thấy trong bộ điều khiển ở điểm cuối thứ hai của sản phẩm, chúng tôi tìm nạp dữ liệu từ bộ nhớ cache của tất cả các sản phẩm, sau đó lọc bằng id sản phẩm và nếu có thì trả về người dùng từ bộ nhớ cache và nếu sau đó không tìm nạp từ cơ sở dữ liệu và trở lại người dùng sau khi áp dụng bộ lọc.
Vì vậy, như bạn thấy bên trong cập nhật, xóa và đăng điểm cuối của Bộ điều khiển sản phẩm, sau đó chúng tôi sử dụng phương pháp loại bỏ để xóa dữ liệu của khóa sản phẩm có bên trong bộ nhớ cache. Vì vậy, có rất nhiều tình huống và cách sử dụng bộ nhớ đệm mà bạn có thể sử dụng tùy theo nhu cầu và yêu cầu của mình. Tôi chỉ muốn giới thiệu những điều cơ bản về Memory Cache và cách nó hoạt động bên trong .NET Core mà tôi đã trình bày ở đây.
Ngoài ra, có một tình huống bạn cần quan tâm khi sử dụng bộ nhớ đệm, chẳng hạn như giả sử, có hai người dùng sử dụng ứng dụng của bạn thì các tình huống sau sẽ xảy ra
Thêm tạo một đối tượng khóa trên cùng của lớp và sau đó trong phương thức như tôi đã hiển thị bên dưới
private static object _lock = new object();
public IEnumerable < Product > Get() {
var cacheData = _cacheService.GetData < IEnumerable < Product >> ("product");
if (cacheData != null) {
return cacheData;
}
lock(_lock) {
var expirationTime = DateTimeOffset.Now.AddMinutes(5.0);
cacheData = _dbContext.Products.ToList();
_cacheService.SetData < IEnumerable < Product >> ("product", cacheData, expirationTime);
}
return cacheData;
}
Vì vậy, ở đây như bạn thấy đầu tiên, chúng tôi kiểm tra xem dữ liệu có bên trong bộ đệm hay không nếu dữ liệu có sẵn thì trả về. Tiếp theo, nếu giá trị không có trong bộ nhớ đệm, thì chúng tôi áp dụng khóa ở đó và sau đó yêu cầu được khóa và nhập vào phần và tìm nạp chi tiết sản phẩm từ cơ sở dữ liệu, sau đó cũng đặt nó vào bộ đệm và sau đó trả lại dữ liệu. Vì vậy, khi người dùng thứ hai gửi yêu cầu trước khi yêu cầu của người dùng đó hoàn tất. Vì vậy, trong trường hợp đó, yêu cầu thứ hai nằm trong hàng đợi và sau khi hoàn thành yêu cầu người dùng đầu tiên, yêu cầu thứ hai xuất hiện trong hình
Đây là tất cả về Bộ nhớ đệm trong Bộ nhớ trong .NET Core. Tôi hy vọng bạn hiểu những điều liên quan đến điều đó.
Nguồn: https://www.c-sharpcorner.com/article/implement-in-memory-cache-in-the-net-core-api/
#aspdotnet #api #csharp #dotnet
1602560783
In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.
To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.
Sub-topics discussed :
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).
From new project window, Select Asp.Net Core Web Application_._
Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.
Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.
Now let’s define DB model class file – /Models/TransactionModel.cs.
public class TransactionModel
{
[Key]
public int TransactionId { get; set; }
[Column(TypeName ="nvarchar(12)")]
[DisplayName("Account Number")]
[Required(ErrorMessage ="This Field is required.")]
[MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
public string AccountNumber { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Beneficiary Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BeneficiaryName { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Bank Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BankName { get; set; }
[Column(TypeName ="nvarchar(11)")]
[DisplayName("SWIFT Code")]
[Required(ErrorMessage = "This Field is required.")]
[MaxLength(11)]
public string SWIFTCode { get; set; }
[DisplayName("Amount")]
[Required(ErrorMessage = "This Field is required.")]
public int Amount { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }
}
C#Copy
Here we’ve defined model properties for the transaction with proper validation. Now let’s define DbContextclass for EF Core.
#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup
1602564619
User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.
Sub-topics discussed :
ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.
ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.
The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.
First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.
Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.
#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core
1587917446
#api #api 2 #restful api #asp.net api #asp.net core api
1583377668
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework
1583378723
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework