在Asp.Net Core中使用CouchBase实现分布式缓存

Couchbase可以实现Redis的缓存功能同时还可以对数据进行持久化,存入到硬盘中,能够实现水平伸缩,并且对于数据的读写来说都能提供低延迟的访问,Couchbase是基于文档或者是JSON格式数据的存储的数据库。

下面说明如何在Asp.Net Core中使用CouchBase Server实现分布式缓存:

首先新建一个Asp.Net Core Web应用程序,选择MVC模板,我讲它命名为CouchBaseMVCTest。

为了集成CouchBase,在这里需要在NuGet中安装Couchbase.Extensions.Caching,如下:

 

现在打开Startup.cs项目中的 文件。需要在ConfigureServices此处为方法添加一些设置代码 。

services.AddCouchbase(opt =>
{
opt.Servers = new List<Uri>
{
new Uri("http://********:8091")
};
opt.Username = "couchtest";
opt.Password = "******";
});
services.AddDistributedCouchbaseCache("infoqcache", opt => { });

AddCouchbase是用来连接CouchBase Server服务器的,AddDistributedCouchbaseCache用来指定服务器上新建的Bucket来作为缓存存储桶。

 这里配置自己安装的CouchBase服务器IP及账号密码。文件顶部添加引用如下:

using Couchbase.Extensions.Caching;
using Couchbase.Extensions.DependencyInjection;  

下面我们来简单的使用CouchBase实现分布式缓存。

首先,将IDistributedCacheas参数添加到构造函数中:

public class HomeController : Controller
 {
    private IDistributedCache _cache;

    public HomeController(IDistributedCache cache)
    {
    	_cache = cache;
    }
 }  

下面使用ApplicationStopped取消令牌:

applicationLifetime.ApplicationStopped.Register(() =>
            {
                app.ApplicationServices.GetRequiredService<ICouchbaseLifetimeService>().Close();
            });  

添加引用using IApplicationLifetime = Microsoft.Extensions.Hosting.IApplicationLifetime;

先简单的测试连接服务器,在Home控制器中加入如下代码:

public IActionResult Index()
{
_cache.Set("CacheTime", System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString()));
ViewData["Message"] = "Your application description page. "
+ System.Text.Encoding.UTF8.GetString(_cache.Get("CacheTime"));
return View();
}  

运行项目:

 

 

 图中时间就是我们刚刚存入infoacache桶中的,key为CacheTime的时间

查看CouchBase Server服务器,如下,可以看到我们新建的桶里有一个项目:

 

 

 

 

下面我们新建一个类parson:

public class Parson
    {
        
        public string Id { get; set; }
        public string FullName { get; set; }
    }

  

加入如下代码:

var obj = new List<Parson>() { new Parson { Id = "1111", FullName = "zyy" },
                new Parson { Id = "1112", FullName = "zyy2" }
            };
            //注意:如果直接使用object来保存,则Couchbase缓存会帮我们自动加密(Base64)
            //如果先序列化后,再保存,那么就不会加密
            _cache.Set("test1", serialize(obj));
            ViewData["Message"] = "Your application description page. "
                        + System.Text.Encoding.UTF8.GetString(_cache.Get("test1"));
            return View();

 结果如下:

 

 

 

 

 

 

 在Couchbase中,数据可以存储为key-value对或者json文档,不需要预先定义严格的格式,由于这种特性,couchbase支持以 scale out(水平扩展)方式扩展数据量,提升io性能,只需要在集群中添加更多的服务器就行了。相反,关系数据库管理系统scale up(纵向扩展),通过加更多的CPU,内存和硬盘以扩展容量。

posted @ 2020-03-01 19:43  圆圆酥  阅读(411)  评论(0编辑  收藏  举报