.NET

컬렉션을 위한 .NET 캐싱 공급자 확장

4 분 읽기

To help .NET developers better use Couchbase in their applications, there is a collection of community-supported Couchbase Extensions. These include extensions for caching, session, multiop, compression, and locking. And there are some officially supported extensions for dependency injection, open telemetry, and transactions.

The main extension for discussion today is Couchbase.Extensions.Caching, which implements the .NET Distributed Cache interface using Couchbase. This can be added to your project with NuGet (dotnet add package Couchbase.Extensions.Caching).

Recently, I was working with a customer in the cruise industry that is managing several applications, and wants to store caching data separately for each application. However, creating an entirely new bucket for each application is overkill. They were wondering how to specify a scope/collection when using the Couchbase.Extensions.Caching library.

Session and Caching Extensions

In recent years, the shift from Couchbase SDK 2 to SDK 3 introduced many new features and improvements, including scopes/collections support. The Couchbase.Extensions family has also been updated to support SDK 3.

However, the 기본값 usage of this library uses the _default scope and _default collection, with no built-in option to specify anything else.

To see this in action, here’s the line of configuration to add Couchbase as a distributed cache (taken from the GitHub example project):

In that code, myproject is a bucket name. The opt object doesn’t have an option for scope/collection name.

Using the sample project, you’ll end up with cached information like this:

(Notice the bucket, scope, and collection names are myproject, _default, 그리고 _default).

Extending the Extension

Thankfully, the library is extensible enough that with a little bit of code, it can be pointed to whatever collection you’d like.

Let’s look a little deeper at the project, specifically ICouchbaseCacheCollectionProvider.cs 그리고 DefaultCouchbaseCacheCollectionProvider.cs

  • ICouchbaseCacheCollectionProvider contains one method, GetCollectionAsync.
  • DefaultCouchbaseCacheCollectionProvider’s implements that method with: return bucket.DefaultCollection();

But what if you don’t want to use the default collection?

In that case, create a custom implementation of ICouchbaseCacheCollectionProvider. I’ll call mine CustomCouchbaseCacheCollectionProvider:

Consider this a starting point. In your implementation, you can set it up however you’d like, add additional logic, etc.

The next step is to add that as a service (in Program.cs typically), specifying the scope/collection names:

If you’re concerned about this being overwritten by the default provider, note that TryAddSingleton is used inside of AddDistributedCouchbaseCache. This means that it won’t override your custom provider with the default provider.

Custom Provider in Action

This extension will not actually create the specified scope and collection, so make sure you’ve created them ahead of time.

Run the app, and try out the Weather Forecast API with the OpenAPI interactive page. The first time executing the endpoint will result in a “cache miss”, at which point the weather forecast data will be written to the collection specified:

(Notice the bucket, scope, and collection names are myproject, mycachingscope, 그리고 mycachingcollection).

요약

With a custom implementation of an interface, and one extra line in Program.cs, you can specify whatever scope/collection you want to store cached data into.

Further, the Couchbase.Extensions.Session extension uses the caching extension as the underlying storage mechanism.

이 기사 공유하기

작가

매튜 D. 그로브스는 코딩을 정말 좋아하는 사람입니다. C#, jQuery, PHP 등 어떤 언어든 상관없이, 그는 무엇이든 풀 리퀘스트를 제출합니다. 그는 90년대에 부모님이 운영하던 피자 가게를 위해 QuickBASIC으로 POS(판매 시점 관리) 앱을 개발한 이래로 줄곧 전문 프로그래머로 활동해 왔습니다. 현재는 Couchbase에서 선임 제품 마케팅 매니저로 근무하고 있습니다. 여가 시간에는 가족과 함께 시간을 보내거나, 레즈(Reds) 경기를 관람하며, 개발자 커뮤니티 활동에 참여합니다. 그는 『AOP in .NET』과 『Pro Microservices in .NET』의 저자이자 Pluralsight 저자이며, Microsoft MVP이기도 합니다.

댓글 남기기

카우치베이스 카펠라를 시작할 준비가 되셨나요?

개발 시작하기

NoSQL을 탐색하고, 리소스를 찾아보고, 튜토리얼을 시작하려면 개발자 포털을 확인하세요.

카펠라 프리 사용하기

단 몇 번의 클릭으로 카우치베이스(Couchbase)를 직접 체험해 보세요. Capella DBaaS는 시작하기 가장 쉽고 빠른 방법입니다.

연락해

Couchbase 제품군에 대해 더 알고 싶으신가요? 저희가 도와드리겠습니다.