编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

.NET Core中的分布式缓存和负载均衡

wxchong 2024-06-24 19:42:00 开源技术 11 ℃ 0 评论

私信我或关注微信号:狮范儿,回复:学习,获取免费学习资源包。

通过减少生成内容所需的工作,缓存可以显著提高应用的性能和可伸缩性,缓存对不经常更改的数据效果最佳,缓存生成的数据副本的返回速度可以比从原始源返回更快。

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,两个网站里的内容改成不一样。



效果图



来源网络,侵权联系删除

私信我或关注微信号:狮范儿,回复:学习,获取免费学习资源包。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表