キャッシュ内の絶対データの有効期限
絶対有効期限 NCache キャッシュアイテムをクライアントが指定した正確な日時で無効化することで、データの一貫性を確保します。キャッシュに一定期間のみ保持する必要があるアイテムには、絶対有効期限を指定できます。たとえば、ある企業が特定の商品について24時間限定のフラッシュセールを実施するとします。これらのアイテムは、24時間の絶対有効期限を設定してキャッシュに保存することで、セール終了後すぐにキャッシュから削除されます。
またこれ DateTime 値はに変換されます UTC時間 キャッシュサーバーとクライアントが異なるタイムゾーンにある場合にも対応します。そのため、アイテムはユーザーが指定した正確な時刻に期限切れになります。
前提条件
使用する前に NCache クライアント側APIについては、以下の前提条件が満たされていることを確認してください。
- Java クライアント アプリケーションに次の Maven 依存関係を追加します。
pom.xml ファイル:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<!--for NCache Enterprise-->
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- .NET クライアント アプリケーションに次のいずれかの NuGet パッケージをインストールします。
- エンタープライズ:
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- 新しいコンソール アプリケーションを作成します。
- 追加するデータが シリアライズ可能.
- 追加 NCache 参考情報 見つけることによって
%NCHOME%\NCache\bin\assembly\4.0 と追加 Alachisoft.NCache.Web (NAIST) と Alachisoft.NCache.Runtime 適切に。
- を含める
Alachisoft.NCache.Web.Caching アプリケーション内の名前空間。
- の詳細については NCache レガシーAPIをダウンロードしてください NCache 4.9 文書は .zip 上のファイル Alachisoft ウェブサイト.
絶対有効期限のあるアイテムを追加または更新する方法
Insert 標準です NCache アプリケーションの状態をキャッシュと同期するための API。キャッシュアイテムを簡単に追加または更新して有効期限を設定できます。 インサート 方法。 ザ CacheItem によって提供されるカスタムクラスです NCache これは、キャッシュにデータを追加するために使用できるだけでなく、オブジェクトに関連付けられた追加のメタデータを設定することもできます。このメタデータは、有効期限、依存関係など、アイテムのプロパティを定義します。
次の例では、の値を設定します Expiration 物件を5分間の絶対有効期限まで CacheItem. それは以下を追加します CacheItem キーが存在しない場合はキャッシュに書き込み、存在する場合は更新します。 CacheItem 5 分後にキャッシュから削除されます。
try
{
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);
// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";
// Create a new CacheItem for this product
var cacheItem = new CacheItem(product);
// Set Expiration TimeSpan
var expiration = new Expiration(ExpirationType.Absolute, TimeSpan.FromMinutes(5));
cacheItem.Expiration = expiration;
// Add/Update item with expiration
cache.Insert(key, cacheItem);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
try
{
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);
// Generate a unique cache key for this product
String key = "Product:" + product.getProductID();
// Create a new CacheItem for this product
CacheItem cacheItem = new CacheItem(product);
// Set Expiration type and TimeSpan
Expiration expiration = new Expiration(ExpirationType.Absolute, TimeSpan.FromMinutes(5));
cacheItem.setExpiration(expiration);
// Add/Update item in cache with expiration
cache.insert(key, cacheItem);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like IllegalArgumentException or NullPointerException
}
try:
# Precondition: Cache is already connected
# Get product from database against given product ID
product = fetch_product_from_db()
# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()
# Create a new CacheItem for this product
cache_item = ncache.CacheItem(product)
# Set Expiration type and TimeSpan
expiration = ncache.Expiration(ncache.ExpirationType.ABSOLUTE, ncache.TimeSpan.from_minutes(5))
cache_item.set_expiration(expiration)
# Add/Update item in cache with expiration
cache.insert(key, cache_item)
except Exception as error:
# Exception can occur due to:
# Connection Failures
# Operation Timeout
# Operation during state transfer
print("An error occurred:", str(error))
try
{
// This is an async method
// Precondition: Cache is already connected
// Get product from database against given product ID
var product = this.fetchProductFromDB(1001);
// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();
// Create a new CacheItem for this product
// You also need to specify the FQN (Fully Qualified Name) of the class
var cacheItem = new ncache.CacheItem(product,"FQN.Product");
// Set Expiration type and TimeSpan
var expiration = new ncache.Expiration(ncache.ExpirationType.Absolute, ncache.TimeSpan.FromMinutes(5));
cacheItem.setExpiration(expiration);
// Add/Update item in cache with expiration
await this.cache.insert(key, cacheItem);
}
catch (error)
{
// Handle errors
}
// Using NCache Enterprise 4.9.1
try
{
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);
// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";
CacheItem cacheItem = new CacheItem(product);
// Updating absolute expiration of 5 min through Add API.
cache.Insert(key, product, null, System.DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Default);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
お願い
操作がフェイルセーフであることを保証するために、で説明されているように、アプリケーション内の潜在的な例外を処理することをお勧めします。 失敗の処理.
使い方 DefaultAbsolute 設定された値を通じてデータを管理できます NCache 管理センターまたは config.ncconf アプリケーションコードの再デプロイを必要とせずに、APIで絶対有効期限を指定できます。 DefaultAbsolute (NAIST) と DefaultAbsoluteLonger。 これにより、必要に応じて、コードを変更せずに値を外部から変更できる柔軟性が得られます。
次のコードは、設定されたデフォルトの有効期限(DefaultAbsolute (この場合)アイテムとキーを照合し、キーが存在しない場合はキャッシュに追加し、キーが存在する場合は有効期限付きでアイテムを更新します。設定された時間が経過すると、アイテムは期限切れになります。
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);
// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";
// Create a CacheItem instance for the product
var cacheItem = new CacheItem(product);
// Set Expiration type
var expiration = new Expiration(ExpirationType.DefaultAbsolute);
cacheItem.Expiration = expiration;
// Add/Update the item in the cache with default expiration
CacheItemVersion version = cache.Insert(key, cacheItem);
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);
// Generate a unique cache key for this product
String key = "Product:" + product.getProductID();
// Create a CacheItem instance for the product
CacheItem cacheItem = new CacheItem(product);
// Set Expiration type
Expiration expiration = new Expiration(ExpirationType.DefaultAbsolute);
cacheItem.setExpiration(expiration);
// Add/Update the item in the cache with default expiration
CacheItemVersion version = cache.insert(key, cacheItem);
# Precondition: Cache is already connected
# Get product from database
product = fetch_product_from_db()
# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()
# Create a new CacheItem for this product
cache_item = ncache.CacheItem(product)
# Set Expiration type and TimeSpan
expiration = ncache.Expiration(ncache.ExpirationType.DEFAULT_ABSOLUTE)
cache_item.set_expiration(expiration)
# Add/Update item in cache with expiration
version = cache.insert(key, cache_item)
// Precondition: Cache is already connected
// This is an async method
// Get product from database against given product ID
var product = this.fetchProductFromDB(1001);
// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();
// Create a CacheItem instance for the product
// You also need to specify the FQN(Fully Qualified Name) of the class
var cacheItem = new ncache.CacheItem(product,"FQN.Product");
// Set Expiration TimeSpan
var expiration = new ncache.Expiration(ncache.ExpirationType.DefaultAbsolute);
cacheItem.setExpiration(expiration);
var version = await this.cache.insert(key, cacheItem);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = FetchProductFromDB("1001");
// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";
CacheItem cacheItem = new CacheItem(product);
// Updating absolute expiration of 5 min through Add API.
cache.Insert(key, product, null, Cache.DefaultAbsolute, Cache.NoSlidingExpiration, CacheItemPriority.Default);
既存のキャッシュアイテムの絶対有効期限を設定する方法
NCache また、既存のキャッシュアイテムをキャッシュに再挿入することなく、絶対有効期限を設定できる柔軟性も提供します。これは、 CacheItemAttributes クラス、 AbsoluteExpiration キャッシュアイテムに設定するプロパティ。これにより、キャッシュ内のアイテムが無効化される正確な日時が設定されます。次に、この属性はアイテムの既存のキーに適用されます。 UpdateAttributes 方法 ICache.
次の例では、キャッシュ内に既に存在し、有効期限が設定されていないアイテムに対して、絶対有効期限を設定します。これにより、アイテムをキャッシュに再追加または再挿入する必要がなくなります。
// Precondition: Cache is already connected
// Precondition: Item already exists in cache
string key = "Product:1001";
// Create a CacheItemAttribute for absolute expiration and set its value to 5 seconds
var attr = new CacheItemAttributes();
attr.AbsoluteExpiration = DateTime.Now.AddSeconds(5);
// Set Absolute Expiration of 5 seconds against existing key
cache.UpdateAttributes(key, attr);
// Precondition: Cache is already connected
// Precondition: Item already exists in cache
String key = "Product:1001";
// Create a CacheItemAttribute for absolute expiration and set its value to 5 seconds
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 5);
CacheItemAttributes attr = new CacheItemAttributes();
attr.setAbsoluteExpiration(calendar.getTime());
// Set Absolute Expiration of 5 seconds against existing key
cache.updateAttributes(key, attr);
# Precondition: Cache is already connected
# Precondition: Item already exists in cache
key = "Product:1001"
# Create a CacheItemAttribute for absolute expiration and set its value to 5 seconds
time = datetime.now() + timedelta(seconds=5)
attr = ncache.CacheItemAttributes()
attr.set_absolute_expiration(time)
# Set Absolute Expiration of 5 seconds against existing key
cache.update_attributes(key, attr)
// This is an async method
// Precondition: Cache is already connected
// Precondition: Item already exists in cache
var key = "Product:1001";
// Create a CacheItemAttribute for absolute expiration and set its value to 5 seconds
var time = new Date().getSeconds()+5;
var attr = new ncache.CacheItemAttributes();
attr.setAbsoluteExpiration(time);
// Set Absolute Expiration of 5 seconds against existing key
await this.cache.updateAttributes(key, attr);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Precondition: Item already exists in cache
string key = "1001";
// Get product from database against given product ID
Product product = FetchProductFromDB(key);
//updating AbsoluteLonger expiration with configured value
cache.Insert(key, product, null, Cache.DefaultAbsoluteLonger, Cache.NoSlidingExpiration, CacheItemPriority.Default);
その他のリソース
NCache の絶対有効期限のサンプルアプリケーションを提供します GitHub.
も参照してください
。ネット: Alachisoft.NCache.ランタイム.キャッシュ 名前空間
Java: com.alachisoft.ncache.runtime.caching 名前空間
Python: ncache.runtime.caching モジュールを開きます。
Node.js: 満了 とに提供されます。