A custom ASP.NET Core Middleware plugin for a distributed cache using Couchbase server as the backing store. Supports both Ephemeral (in-memory) and Couchbase (persistent) buckets.
Assuming you have an installation of Couchbase Server and Visual Studio (examples with VSCODE forthcoming), do the following:
- Create a .NET Core Web Application using Visual Studio or VsCodeor CIL
- Install the package from NuGet or build from source and add reference
In Setup.cs add the following to the ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCouchbase(opt =>
{
opt.ConnectionString = "couchbase://localhost";
opt.Username = "Administrator";
opt.Password = "password";
});
services.AddDistributedCouchbaseCache("default", opt => { });
}
You can change the localhost
hostname to wherever you are hosting your Couchbase cluster.
In your controller add a parameter for IDistributedCache
to the constructor:
public class HomeController : Controller
{
private IDistributedCache _cache;
public HomeController(IDistributedCache cache)
{
_cache = cache;
}
public async Task<IActionResult> Index()
{
await _cache.SetAsync("CacheTime", System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString()));
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page. "
+ System.Text.Encoding.UTF8.GetString(_cache.Get("CacheTime"));
return View();
}
}
For performance reasons, we strongly recommend using the Async overloads and not the sychronous methods on IDistributeCache.