Distributed caching can help to improve performance of an ASP.NET Core application. This is especially true for an ASP.NET application that’s deployed to a server farm or scalable cloud environment. Using Couchbase Server for caching is one of the many features that make it an ideal choice for your engagement database needs.

In this blog post, I’ll show you how to use the Couchbase.Extensions.Caching middleware plugin to easily add distributed caching capabilities to your application.

You can follow along with the sample code I wrote for this post on GitHub.

Please note that Couchbase.Extensions.Caching is currently in a beta2 release (as I’m writing this blog post), so some things may change.

Basic setup of Couchbase

First, you’ll need a Couchbase Server cluster running (you can install it on-premise, or with Docker, or even in Azure if you’d like).

Next, you’ll need to create a bucket in Couchbase where cached data will be stored. I called mine “cachebucket”. You may want to take advantage of the new ephemeral bucket feature in Couchbase Server 5.0 for caching, but it is not required.

If you are using Couchbase Server 5.0, you’ll also need to create a user with permissions (Data Writer and Data Reader) on that bucket. To keep things simple, create a user that has the same name as the bucket (e.g. “cachebucket”).

Distributed Caching with Couchbase.Extensions

The Couchbase.Extensions (GitHub) project aims to make working with Couchbase Server and .NET Core simpler. Caching is just one of these extensions.

You can add it to your ASP.NET Core project with NuGet, via Package Manager: Install-Package Couchbase.Extensions.Caching -Version 1.0.0-beta2, or with the NuGet UI, or you can use the .NET command line: dotnet add package Couchbase.Extensions.Caching --version 1.0.0-beta2.

Couchbase extension for distributed caching available on NuGet

Once you’ve added this to your project, you’ll need to make a couple minor changes to your Startup class in Startup.cs.

First, in ConfigureServices, add a couple namespaces:

This will make the Caching namespace available, and specifically the AddDistributedCouchbaseCache extension method for IServiceCollection. Next, call that extension method from within the ConfigureServices method.

The other namespace in there, DependencyInjection, is necessary to inject Couchbase functionality. In this case, it’s going to be used only by the Caching extension. But you can use it for other purposes too, which I will cover in a future blog post.

But for now, it’s just needed for the AddCouchbase extension method on IServiceCollection.

Finally, put them both together, and your ConfigureServices method should look like this:

Using distributed caching

Now that you have distributed caching setup with Couchbase in your ASP.NET Core project, you can use IDistributedCache elsewhere in your project.

Injecting IDistributedCache

A simple example would be to use it directly in a controller. It can be injected into constructors as you need it:

Caching strings

You can use the GetString and SetString methods to retrieve/set a string value in the cache.

This would appear in the “cachebucket” bucket as an encoded binary value (not JSON).

String cached in Couchbase

In the sample code, I simply print out the ViewData["Message"] in the Razor view. It should look something like this:

Cached string output to Razor

Caching objects

You can also use Set<> and Get<> methods to save and retrieve objects in the cache. I created a very simple POCO (Plain Old CLR Object) to demonstrate:

Next, in the sample, I generate a random string to use as a cache key, and a random generated instance of MyPoco. First, I store them in the cache using the Set<> method:

Then, I print out the key to the Razor view:

Cached POCO output to Razor

Next, I can use this key to look up the value in Couchbase:

Cached POCO in Couchbase

Also, notice that it’s been serialized to JSON. This not only means that you can read it, but you can also query it with N1QL (if you need to).

Distributed caching with expiration

If you want the values in the cache to expire after a certain period of time, you can specify that with DistributedCacheEntryOptions (only SlidingExpiration is supported at this time).

In the sample project, I’ve also set this to print out to Razor.

Cached POCO with expiration

If you view that document (before the 10 seconds runs out) in Couchbase Console, you’ll see that it has an expiration value in its metadata. Here’s an example:

After 10 seconds, that document will be gone from the bucket, and you’ll see an error “not found (Document does not exist)”.

Tearing down distributed caching

Finally, don’t forget to cleanup the resources used by the Couchbase .NET SDK for distributed caching. One easy way to do this is with the ApplicationStopped event. You can wire this up in Startup:

Note that you will have to add IApplicationLifetime appLifetime as a parameter to the Configure method in Startup if you haven’t already.

Summary

Using Couchbase Server for distributed caching in your ASP.NET Core application is a great way to improve performance and scalability in your application. These kind of “engagement” use cases are what Couchbase Server excels at. To see customers that are using Couchbase Server for caching, check out the Couchbase Customers page.

If you have questions or comments about the Couchbase.Extensions.Caching project, make sure to check out the GitHub repository or the Couchbase .NET SDK forums.

As always, you can reach me by leaving a comment below or finding me on Twitter @mgroves.

Author

Posted by Matthew Groves

Matthew D. Groves is a guy who loves to code. It doesn't matter if it's C#, jQuery, or PHP: he'll submit pull requests for anything. He has been coding professionally ever since he wrote a QuickBASIC point-of-sale app for his parent's pizza shop back in the 90s. He currently works as a Senior Product Marketing Manager for Couchbase. His free time is spent with his family, watching the Reds, and getting involved in the developer community. He is the author of AOP in .NET, Pro Microservices in .NET, a Pluralsight author, and a Microsoft MVP.

3 Comments

  1. Mathew,

    This was a nice article about getting started with the couchebase. I tried downloading the couchebase server locally for studying and I was able to implement the caching in a dotnet core app using the provided middleware. The only problem I have right now is with the older version of couchebase at my workplace. They happen to have old couchebase server that does not have password protected security at bucket level and when I am trying to
    services.AddCouchbase(opt =>
    {
    opt.Servers = new List
    {
    new Uri(“http://myworkplacecouchebasehostname:8091”)
    };
    });
    //no password for bucket, so se
    services.AddDistributedCouchbaseCache(“bucketname”, opt => {});

    I get the following error with stacktrace,can you please point me in the right direction o what I am missing here:
    An unhandled exception occurred while processing the request.
    BootstrapException: Could not bootstrap – check inner exceptions for details. (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond) (Could not bootstrap with CCCP. (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond)) (After bootstrapping the nodes list has zero elements indicating that client failed during bootstrapping. Please check the client logs for more information as for why it failed.)
    Couchbase.Core.ClusterController.CreateBucketImpl(string bucketName, string password, IAuthenticator authenticator)

    SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
    Couchbase.IO.DefaultConnectionFactory+c__0.b__0_0(IConnectionPool p, IByteConverter c, BufferAllocator b)

    CouchbaseBootstrapException: After bootstrapping the nodes list has zero elements indicating that client failed during bootstrapping. Please check the client logs for more information as for why it failed.
    Couchbase.Configuration.CouchbaseConfigContext.UpdateServices(Dictionary servers)

    SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
    Couchbase.IO.DefaultConnectionFactory+c__0.b__0_0(IConnectionPool p, IByteConverter c, BufferAllocator b)

    1. Hi zysed,

      I’d recommend you post this question to the .NET forums: https://forums.couchbase.com/c/net-sdk or possibly as an issue to the Extensions library: https://github.com/couchbaselabs/Couchbase.Extensions

      There is probably a workaround, and posting to those places will get mores eyes on it than just mine.

      I would highly recommend getting a password on your bucket or upgrading to a newer version of Couchbase Server (where it’s no longer possible to have a bucket without a password). Even if your server is behind a firewall, it’s still dangerous to leave it completely unsecured. And further, such an old version of Couchbase is likely to stop getting bug fix releases (if it hasn’t already).

  2. Thanks Matthew. Also, I completely agree. Once again, please keep writing nice articles like this as they are very helpful.

Leave a reply