通過減少生成內容所需的工作,緩存可以顯著提高應用的性能和可伸縮性,緩存對不經常更改的數據效果最佳,緩存生成的數據副本的返回速度可以比從原始源返回更快。ASP.NET Core 支持多種不同的緩存,最簡單的緩存基於 IMemoryCache,它表示存儲在 Web 服務器內存中的緩存。 在包含多個服務器的場合,要保證緩存數據的一致性,這個時候需要分布式緩存,也就是把數據從緩存內存中保存到外部緩存服務器中,例如reids,雲等,內存中和分布式緩存將緩存項存儲為鍵 / 值對。
創建.net core項目
修改Startup.cs
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ////內存中緩存,完全可以替代session //services.AddMemoryCache(); //redis分布式緩存 services.AddDistributedRedisCache(options => { options.Configuration = "127.0.0.1:32768";//redis的端口地址 options.InstanceName = "simple"; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
修改HomeController.cs
public class HomeController : Controller { #region 內存中緩存 //private IMemoryCache _cache; //public HomeController(IMemoryCache memoryCache) //{ // _cache = memoryCache; //} #endregion private readonly IDistributedCache _cache; public HomeController(IDistributedCache cache) { _cache = cache; } public IActionResult Index() { return View(); } [HttpPost] public JsonResult SetSession(string key, string value) { //_cache.Set(key, value); //內存中緩存 _cache.SetString(key, value); return Json(new { success = true }); } [HttpGet] public IActionResult GetSession(string key) { //string value = _cache.Get<string>(key); //內存中緩存 string value = _cache.GetString(key); return Json(new { success = true, data = value }); } }
Nginx負載均衡
nginx的安裝這里不做講解,下載安裝就可以了,redis的安裝這里也不做講解。nginx配置如下
#user nobody; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; #項目發布的地址 upstream myredis.run { server 127.0.0.1:8081; server 127.0.0.1:8082; } server { listen 8084; #端口 server_name localhost; #網址 location / { root html; index index.html index.htm; proxy_pass http://myredis.run; #需要與upstream后面的一致 } #error_page 404 /404.html; } }
網站配置
網址2設置,網站1同樣設置,訪問localhost:8084可以看到效果,刷新頁面訪問到網站1和網站2,兩個網站里的內容改成不一樣。
效果圖
源碼地址
https://github.com/jasonhua95/samll-project/tree/master/DistributedSession
其他分布式文章
不同的分布式文章,用actor實現分布式,Actor模型(分布式編程)。