クライアントについて
EnyimMemcachedCore は、EnyimMemcached から .NET Core に移行された Memcached クライアントです。このクライアントは .NET Core をサポートしています。
GitHub でホストされているソースコードのアドレス: https://github.com/cnblogs/EnyimMemcachedCore
NuGet パッケージのアドレス: https://www.nuget.org/packages/EnyimMemcachedCore
1. NuGet パッケージをインストールする
Install-Package EnyimMemcachedCore2. NuGet パッケージを構成する
2.1 appsetting.json で NuGet パッケージを構成する
検証なしの構成
{ "enyimMemcached": { "Servers": [ { "Address": "memcached", "Port": 11211 } ] } }検証ありの構成
{ "enyimMemcached": { "Servers": [ { "Address": "memcached", "Port": 11211 } ], "Authentication": { "Type": "Enyim.Caching.Memcached.PlainTextAuthenticator", "Parameters": { "zone": "", "userName": "username", "password": "password" } } } }Startup.cs の構成コード
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddEnyimMemcached(options => Configuration.GetSection("enyimMemcached").Bind(options)); // サービスに EnyimMemcached を追加し、appsettings.json から設定を読み込みます。 } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseEnyimMemcached(); // EnyimMemcached ミドルウェアを使用します。 } }
2.2 構成ファイルなしで NuGet パッケージをハードコーディングする
Startup.cs で構成コードをハードコーディングする
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddEnyimMemcached(options =>
{
options.AddServer("memcached", 11211); // Memcached サーバーを追加します。
//options.AddPlainTextAuthenticator("", "usename", "password"); // 必要に応じてプレーンテキスト認証を追加します。
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseEnyimMemcached(); // EnyimMemcached ミドルウェアを使用します。
}
}3. NuGet パッケージを呼び出す
3.1 IMemcachedClient 操作を呼び出す
public class TabNavService
{
private ITabNavRepository _tabNavRepository;
private IMemcachedClient _memcachedClient;
public TabNavService(
ITabNavRepository tabNavRepository,
IMemcachedClient memcachedClient)
{
_tabNavRepository = tabNavRepository;
_memcachedClient = memcachedClient;
}
public async Task<IEnumerable<TabNav>> GetAll()
{
var cacheKey = "aboutus_tabnavs_all"; // キャッシュキー
var result = await _memcachedClient.GetAsync<IEnumerable<TabNav>>(cacheKey); // キャッシュからデータを取得しようとします。
if (!result.Success) // キャッシュにデータがない場合
{
var tabNavs = await _tabNavRepository.GetAll(); // データベースからデータを取得します。
await _memcachedClient.AddAsync(cacheKey, tabNavs, 300); // データをキャッシュに追加します。有効期限は 300 秒です。
return tabNavs; // データを返します。
}
else // キャッシュにデータがある場合
{
return result.Value; // キャッシュされたデータを返します。
}
}
}3.2 Microsoft.Extensions.Caching.Abstractions から IDistributedCache 操作を呼び出す
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(); // 取得したデータを CreativeDTO に変換します。
var json = string.Empty; // シリアル化された JSON 文字列を格納する変数
if (creatives != null && creatives.Count() > 0) // データが存在する場合
{
json = JsonConvert.SerializeObject(creatives); // データを JSON 文字列にシリアル化します。
}
await _cache.SetStringAsync(
cacheKey,
json,
new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5))); // データをキャッシュに追加します。有効期限はスライド式で 5 分です。
}
else // キャッシュにデータがある場合
{
creatives = JsonConvert.DeserializeObject<List<CreativeDTO>>(creativesJson); // JSON 文字列をデシリアライズしてデータを取得します。
}
return creatives; // データを返します。
}
}