經過減小生成內容所需的工做,緩存能夠顯著提升應用的性能和可伸縮性,緩存對不常常更改的數據效果最佳,緩存生成的數據副本的返回速度能夠比從原始源返回更快。ASP.NET Core 支持多種不一樣的緩存,最簡單的緩存基於 IMemoryCache,它表示存儲在 Web 服務器內存中的緩存。 在包含多個服務器的場合,要保證緩存數據的一致性,這個時候須要分佈式緩存,也就是把數據從緩存內存中保存到外部緩存服務器中,例如reids,雲等,內存中和分佈式緩存將緩存項存儲爲鍵 / 值對。html
修改Startup.csnginx
// 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.csgit
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的安裝這裏不作講解,下載安裝就能夠了,redis的安裝這裏也不作講解。nginx配置以下github
#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,兩個網站裏的內容改爲不同。redis
https://github.com/jasonhua95/samll-project/tree/master/DistributedSession編程
不一樣的分佈式文章,用actor實現分佈式,Actor模型(分佈式編程)。緩存