通过减少生成内容所需的工作,缓存可以显著提高应用的性能和可伸缩性,缓存对不经常更改的数据效果最佳,缓存生成的数据副本的返回速度可以比从原始源返回更快。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模型(分布式编程)。