Enyim Memcached Client

repository·main·Indexed 41 days ago

https://github.com/cnblogs/enyimmemcachedcore

A .NET library for interacting with Memcached servers that provides a specialized IMemcachedClient interface and implements the standard .NET IDistributedCache interface.

Tokens
2.1K
Snippets
4
Records
4
Agent score
1%

What's inside Enyim Memcached

  1. Register Enyim Memcached in Startup.cs

    main

    To use the client in a .NET application, register it in the ConfigureServices method of your Startup class. The library provides several extension methods for IServiceCollection to support different configuration sources:

    • services.AddEnyimMemcached(): Uses default configuration.
    • services.AddEnyimMemcached(Configuration): Uses the application's IConfiguration.
    • services.AddEnyimMemcached(Configuration, "sectionName"): Uses a specific configuration section.
    • services.AddEnyimMemcached(options => ...): Allows manual configuration via an options delegate.

    Additionally, call app.UseEnyimMemcached() in the Configure method to set up the middleware.

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddEnyimMemcached();
            // Other variations:
            // services.AddEnyimMemcached("enyimMemcached");
            // services.AddEnyimMemcached(Configuration);
            // services.AddEnyimMemcached(Configuration, "enyimMemcached");
            // services.AddEnyimMemcached(Configuration.GetSection("enyimMemcached"));
            // services.AddEnyimMemcached(options => options.AddServer("memcached", 11211));
        }
        
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseEnyimMemcached();
        }
    }
  2. Configure Enyim Memcached via appsettings.json

    main

    You can configure the Memcached client using the appsettings.json file. The configuration supports both unauthenticated connections and connections requiring authentication.

    Without Authentication

    Provide a enyimMemcached section containing a Servers array and a Transcoder.

    With Authentication

    Include an Authentication object within the enyimMemcached section. Specify the Type (e.g., Enyim.Caching.Memcached.PlainTextAuthenticator) and provide the necessary Parameters such as userName and password.

    // Without Authentication
    {
      "enyimMemcached": {
        "Servers": [
          {
            "Address": "memcached",
            "Port": 11211
          }
        ],
        "Transcoder": "MessagePackTranscoder"
      }
    }
    
    // With Authentication
    {
      "enyimMemcached": {
        "Servers": [
          {
            "Address": "memcached",
            "Port": 11211
          }
        ],
        "Authentication": {
          "Type": "Enyim.Caching.Memcached.PlainTextAuthenticator",
          "Parameters": {
            "zone": "",
            "userName": "username",
            "password": "password"
          }
        }
      }
    }
  3. Use the IMemcachedClient interface

    main

    The IMemcachedClient interface provides high-level methods for interacting with Memcached. A common pattern is using GetValueOrCreateAsync, which checks for a key in the cache and, if missing, executes a provided factory function to retrieve the data and then stores it in the cache.

    public class HomeController : Controller
    {
        private readonly IMemcachedClient _memcachedClient;
        private readonly IBlogPostService _blogPostService;
    
        public HomeController(IMemcachedClient memcachedClient, IBlogPostService blogPostService)
        {
            _memcachedClient = memcachedClient;
            _blogPostService = blogPostService;
        }
    
        public async Task<IActionResult> Index()
        {
            var cacheKey = "blogposts-recent";
            var cacheSeconds = 600;
    
            var posts = await _memcachedClient.GetValueOrCreateAsync(
                cacheKey,
                cacheSeconds,
                async () => await _blogPostService.GetRecent(10));
    
            return Ok(posts);
        }
    }
  4. Use the IDistributedCache interface

    main

    Enyim Memcached also implements the standard .NET IDistributedCache interface. This allows you to use standard methods like GetStringAsync and SetStringAsync for distributed caching, which is useful for interoperability with other .NET caching abstractions. When using IDistributedCache, you typically handle serialization (e.g., using JsonConvert) manually.

    public class CreativeService
    {
        private ICreativeRepository _creativeRepository;
        private IDistributedCache _cache;
    
        public CreativeService(ICreativeRepository creativeRepository, IDistributedCache cache)
        {
            _creativeRepository = creativeRepository;
            _cache = cache;
        }
    
        public async Task<IList<CreativeDTO>> GetCreatives(string unitName)
        {
            var cacheKey = $"creatives_{unitName}";
            IList<CreativeDTO> creatives = null;
    
            var creativesJson = await _cache.GetStringAsync(cacheKey);
            if (creativesJson == null)
            {
                creatives = await _creativeRepository.GetCreatives(unitName)
                        .ProjectTo<CreativeDTO>().ToListAsync();
    
                var json = string.Empty;
                if (creatives != null && creatives.Count() > 0)
                {
                    json = JsonConvert.SerializeObject(creatives);
                }
                await _cache.SetStringAsync(
                    cacheKey, 
                    json, 
                    new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5)));
            }
            else
            {
                creatives = JsonConvert.DeserializeObject<List<CreativeDTO>>(creativesJson);
            }
    
            return creatives;
        }
    }