항목에 대한 배타적 잠금(비관적 잠금)
NCache 캐시된 데이터를 배타적으로 잠그는 비관적 잠금 메커니즘을 제공합니다. 이 메커니즘은 다음을 사용하여 항목을 잠급니다. LockHandle이는 다른 모든 사용자가 해당 캐시 항목에 대한 쓰기 작업을 수행하는 것을 방지합니다. LockHandle 캐시에 있는 모든 잠긴 항목과 연결되어 있으며 Locking API에서 반환됩니다. 잠긴 항목은 해당 항목이 활성화된 경우에만 검색, 업데이트 또는 잠금 해제할 수 있습니다. LockHandle API 레벨에서 제공됩니다. 하지만 데이터 무결성 문제를 방지하기 위해 주의해서 사용해야 합니다. 비관적 잠금(Pessimistic Locking)은 데이터 일관성을 보장하는 것이 목표일 때 신뢰할 수 있는 접근 방식입니다. 일단 잠금이 획득되면, LockHandle, 해제하는 두 가지 메커니즘이 있습니다. 이러한 메커니즘은 모두 아래에 설명되어 있습니다.
시간 기반 잠금 해제: 캐시된 항목을 잠글 때 잠금 시간 제한을 지정할 수 있습니다. 잠금 시간 제한은 지정된 시간 간격 동안 잠금 해제를 위한 명시적인 호출이 없을 경우 잠금이 자동으로 해제되는 시간 간격입니다. 이를 통해 데이터가 무기한으로 잠긴 상태로 유지되는 것을 방지할 수 있습니다.
강제 잠금 해제: 분산 환경에서는 캐시 항목에 대한 잠금을 획득한 애플리케이션이 갑자기 종료되거나, 잠금된 데이터에 대한 처리를 완료했지만 잠금을 해제하지 않는 상황이 발생할 수 있습니다. 이러한 경우 해당 애플리케이션이 획득한 잠금을 해제해야 합니다. NCache 캐시 항목에 대한 잠금을 강제로 해제하는 잠금 해제 API를 제공합니다.
주의 사항
그것은 추천 를 사용하는 시간 기반 잠금 지정된 시간이 지나면 아이템이 자동으로 잠금 해제되도록 하는 메커니즘으로, 리소스가 잠겨 있는 시간을 최소화하고 시스템 효율성을 전반적으로 향상시킵니다.
분산 애플리케이션에서 비관적 잠금의 사용 사례
앞서 논의했던 은행 계좌 사례를 생각해 봅시다. 두 명의 사용자가 동시에 같은 은행 계좌에 접근하여 정보를 업데이트하려고 하면 충돌이 발생하여 데이터 불일치가 초래될 수 있습니다.
이 시나리오에서 비관적 잠금(Pessimistic Locking)은 한 번에 한 명의 사용자만 계정에 접근할 수 있도록 합니다. 사용자가 작업을 성공적으로 완료하고 잠금을 해제하면 잠금이 해제되어 두 번째 사용자가 계정에 접근하여 변경 작업을 수행할 수 있게 됩니다. 이 방식을 사용하면 데이터의 일관성이 유지되고 충돌이 발생하지 않습니다.
A LockHandle 잠금 상태인 동안 특정 항목에 캐시 전체에서 접근할 수 없도록 해당 항목과 연결됩니다. NCache 잠금 기능을 위한 구체적인 방법과 잠금 메커니즘을 조작하는 다양한 오버로드 기능을 제공합니다.
사전 조건
사용하기 전에 NCache 클라이언트 측 API를 사용할 때 다음 전제 조건을 충족하는지 확인하십시오.
- .NET 클라이언트 애플리케이션에 다음 NuGet 패키지를 설치하세요.
- 애플리케이션에 다음 네임스페이스를 포함합니다.
- 캐시가 실행 중이어야 합니다.
- 추가되는 데이터가 직렬화 가능.
- API 세부 정보는 다음을 참조하세요. 아이캐시, 포함, 카운트, 끼워 넣다, 로크, 잠금 핸들, 제거, 시간 범위, 자물쇠를 열다, 캐시 아이템, 돈을 받아가세요, 캐시 아이템 가져오기.
- Java 클라이언트 애플리케이션에 대해 다음 Maven 종속성을 추가합니다.
pom.xml 파일 :
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<!--for NCache Enterprise-->
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Java 클라이언트 애플리케이션에서 다음 패키지를 가져옵니다.
- 캐시가 실행 중이어야 합니다.
- 추가되는 데이터가 직렬화 가능.
- API 세부 정보는 다음을 참조하세요. 캐시, 이 포함되어 있습니다, getCount, 삽입하다, 자물쇠, 잠금 핸들, 제거, 시간 범위, 잠금을 해제, getCacheItem, 얻을.
- .NET 클라이언트 애플리케이션에 다음 NuGet 패키지 중 하나를 설치하세요.
- 기업 :
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- 새로운 콘솔 애플리케이션을 만듭니다.
- 추가되는 데이터가 직렬화 가능.
- 추가 NCache 참고자료 위치를 찾아서
%NCHOME%\NCache\bin\assembly\4.0 추가 Alachisoft.NCache.Web Alachisoft.NCache.Runtime 적절한.
- 포함시키다
Alachisoft.NCache.Web.Caching 애플리케이션의 네임스페이스.
- 에 대한 자세한 내용을 보려면 NCache 레거시 API를 다운로드하세요 NCache 4.9 문서는 다음과 같이 사용 가능합니다. .지퍼 에 파일 Alachisoft 웹 사이트.
LockHandle을 사용하여 캐시 항목을 명시적으로 잠그는 방법
작업을 수행하기 전에 항목을 명시적으로 잠글 수 있습니다. 이 방법에는 TimeSpan 지정된 시간 동안 항목을 잠그려면 다음을 지정합니다. 그러나 획득한 잠금이 만료되지 않도록 하려면 다음을 지정합니다. TimeSpan.Zero. 아니라면 TimeSpan 해당 아이템이 제공되면 무기한 잠금 상태가 됩니다.
The Lock 이 예에서 사용된 방법은 LockHandle 열쇠가 있습니다. 단 하나의 열쇠가 있는지 확인하십시오. LockHandle 이 핸들은 하나의 키와 연결되어 있습니다. 핸들을 재사용하기 전에 잠금을 해제해야 합니다. 그렇지 않으면 일관성 없는 동작이 발생할 수 있습니다. 항목이 이미 잠겨 있는 경우 이 메서드는 false를 반환하지만 업데이트된 핸들 정보를 제공합니다. LockHandle.
경고
최소한의 항목 잠금 TimeSpan 교착 상태나 기아 상태를 피하기 위해.
다음 예제는 LockHandle그리고 나서 열쇠로 물건을 잠급니다. Product:1001 A에 대한 TimeSpan 10초입니다. 즉, 10초 후에 아이템이 자동으로 잠금 해제됩니다.
try
{
// Precondition: Cache is already connected
// Item is already added in the cache
// Specify the key of the item
string key = $"Product:1001";
// Create a new LockHandle
LockHandle lockHandle = null;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Lock the item for a timespan of 10 seconds
bool lockAcquired = cache.Lock(key, lockSpan, out lockHandle);
// Verify if the item is locked successfully
if (lockAcquired == true)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
}
catch (OperationFailedException ex)
{
// NCache specific exception can occur due to:
// Connection failures
// Operation performed during state transfer
// Operation timeout
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
try
{
// Precondition: Cache is already connected
// Item is already added in the cache
// Specify the key of the item
String key = "Product:1001";
// Create a new LockHandle
LockHandle lockHandle = new LockHandle();
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
// Lock the item for a timespan of 10 seconds
boolean lockAcquired = cache.lock(key, lockSpan, lockHandle);
// Verify if the item is locked successfully
if (lockAcquired == true)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
}
catch (OperationFailedException ex)
{
// NCache specific exception can occur due to:
// Connection failures
// Operation performed during state transfer
// Operation timeout
}
catch(Exception ex)
{
// Any generic exception like IllegalArgumentException or NullPointerException
}
try:
# Precondition: Cache is already connected
# Item is already added in the cache
# Specify the key of the item
key = "Product:1001"
# Create a new LockHandle
lock_handle = ncache.LockHandle()
# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)
# Lock the item for a timespan of 10 seconds
lock_acquired = cache.lock(key, lock_span, lock_handle)
# Verify if the item is locked successfully
if lock_acquired:
# Item has been successfully locked
else:
# Key does not exist
# Item is already locked with a different LockHandle
except ncache.OperationFailedException as ex:
# NCache specific exception can occur due to:
# - Connection failures
# - Operation performed during state transfer
# - Operation timeout
pass
except Exception as ex:
# Any generic exception
pass
try
{
// This is an async method
// Item is already added in the cache
// Specify the key of the item
var key = "Product:1001";
// Create a new LockHandle
var lockHandle = new ncache.LockHandle();
// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);
// Lock the item for a timespan of 10 seconds
var lockAcquired = await this.cache.lock(key, lockSpan, lockHandle);
// Verify if the item is locked successfully
if (lockAcquired == true)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
}
catch (error)
{
// Handle errors
}
try
{
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Specify the key of the item
string key = $"Product:1001";
// Create a new LockHandle
LockHandle lockHandle = null;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Lock the item for a timespan of 10 seconds
bool lockAcquired = cache.Lock(key, lockSpan, out lockHandle);
// Verify if the item is locked successfully
if (lockAcquired == true)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
}
catch (OperationFailedException ex)
{
// NCache specific exception can occur due to:
// Connection failures
// Operation performed during state transfer
// Operation timeout
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
데이터 검색(가져오기 작업) 중 잠금 획득
캐시에서 아이템을 가져오는 동안 아이템을 잠글 수 있습니다. 즉, 잠금을 해제하기 전까지는 다른 사람이 해당 아이템에 접근할 수 없습니다. 키가 일치하지 않으면 null 값이 반환됩니다.
항목이 잠겨 있지 않은 경우 acquireLock true로 설정하면 해당 아이템을 함께 받게 됩니다. LockHandle.
잘못된 값이나 새로운 값을 입력하면 LockHandle 아이템이 잠겨 있는 동안 또는 acquireLock false로 설정되어 있습니다. null 값이 반환됩니다. 하지만 여전히 다음을 받게 됩니다. LockHandle 그것은 이전에 해당 물건을 잠그는 데 사용되었습니다.
항목이 잠겨 있고 acquireLock false로 설정되어 있지만 올바른 값을 전달했습니다. LockHandle 이전에 해당 항목을 잠그는 데 사용되었던 값을 가져오면 해당 값을 얻을 수 있습니다.
경고
최소한의 항목 잠금 TimeSpan 교착 상태나 스레드 부족 현상을 방지하기 위해서입니다.
이 예에서는 키와 LockHandle 캐시된 객체를 가져와 잠그도록 지정되어 있습니다. 설정해야 합니다. acquireLock 자물쇠를 얻으려면 true를 입력해야 합니다. 이 아이템은 10초 동안 잠겨 있으며, 10초 후에 자동으로 잠금이 해제됩니다.
// Precondition: Cache is already connected
// Set acquireLock flag as true
bool acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Specify the key of the item
string key = $"Product:1001";
// Create a new LockHandle
LockHandle lockHandle = null;
// Lock the item for a timespan of 10 seconds
var result = cache.Get<Product>(key, acquireLock, lockSpan, ref lockHandle);
// Verify if the item is locked successfully
if (result != null)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
// Precondition: Cache is already connected
// Set acquireLock flag as true
boolean acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
// Specify the key of the item
String key = "Product:1001";
// Create a new LockHandle
LockHandle lockHandle = new LockHandle();
// Lock the item for a timespan of 10 seconds
Object result = cache.get(key, acquireLock, lockSpan, lockHandle, Object.class);
// Verify if the item is locked successfully
if (result != null)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
# Precondition: Cache is already connected
# Specify the key of the item
key = "Product:1001"
# Set acquireLock flag as true
acquire_lock = True
# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)
# Create a new LockHandle
lock_handle = ncache.LockHandle()
# Lock the item for a timespan of 10 seconds
result = cache.get_cacheitem(key, acquirelock=acquire_lock, locktimeout=lock_span, lockhandle=lock_handle)
# Verify if the item is locked successfully
if result is not None:
# Item has been successfully locked
else:
# Key does not exist
# Item is already locked with a different LockHandle
// Precondition: Cache is already connected
// Specify the key of the item
var key = "Product:1001";
// Set acquireLock flag as true
var acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);
// Create a new LockHandle
var lockHandle = new ncache.LockHandle();
// Lock the item for a timespan of 10 seconds
// CacheItemVersion set to null and Readthrough Options set to null
var result = await this.cache.getCacheItem(key,null,null, acquireLock, lockSpan, lockHandle);
// Verify if the item is locked successfully
if (result != null)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Specify the key of the item
string key = "Product:1001";
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
// Create a new LockHandle
LockHandle lockHandle = new LockHandle();
// Lock the item for a timespan of 10 seconds
object result = cache.Get(key, lockSpan, ref lockHandle, true);
if (result != null)
{
if (result is Product)
{
Product product = (Product)result;
}
}
업데이트 작업으로 잠금 해제
항목을 업데이트하는 동안 잠금을 해제하여 다른 사용자가 캐시된 데이터에 접근할 수 있도록 할 수 있습니다. 잠긴 항목을 성공적으로 해제하려면 다음을 지정해야 합니다. LockHandle 그것은 원래 물건을 잠그는 데 사용되었습니다.
The LockHandle 해당 아이템을 잠글 때 사용했던 것과 동일한 비밀번호여야 합니다. 그렇지 않으면 "아이템이 잠겨 있습니다"라는 예외 메시지가 표시됩니다.
경우 releaseLock false로 설정되어 있어도 여전히 올바른 값을 전달해야 합니다. LockHandle 항목을 업데이트합니다.
항목이 잠겨 있지 않으면 LockHandle releaseLock 아무런 효과가 없으므로 무시됩니다.
다음 예제는 캐시에 항목을 잠그고, 해당 항목을 사용하여 가져옵니다. LockHandle, 이를 업데이트하고, 를 사용하여 캐시에 다시 삽입합니다. 끼워 넣다 API.
// Precondition: Cache is already connected
// Specify the key of the item
string key = $"Product:1001";
// Set acquireLock flag as true
bool acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
// Initialize the LockHandle
LockHandle lockHandle = null;
CacheItem item = cache.GetCacheItem(key, acquireLock, lockSpan, ref lockHandle);
var product = new Product();
product = item.GetValue<Product>();
// Update the unitsinstock for the product
product.UnitsInStock = 200;
bool releaseLock = true;
// Item is already locked with a LockHandle
// Update the item and release the lock as well since releaseLock is set to true
// Make sure that the LockHandle matches with the already added LockHandle
cache.Insert(key, item, null, lockHandle, releaseLock);
// Precondition: Cache is already connected
// Specify the key of the item
String key = "Product:1001";
// Set acquireLock flag as true
boolean acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
// Initialize the lockHandle
LockHandle lockHandle = new LockHandle();
CacheItem item = cache.getCacheItem(key, acquireLock, lockSpan, lockHandle);
// Update the value of item
product = item.getValue(Product.class);
product.setUnitsInStock(200);
boolean releaseLock = true;
// Item is already locked with a LockHandle
// Update the item and release the lock as well since releaseLock is set to true
// Make sure that the LockHandle matches with the already added LockHandle
cache.insert(key, item, null, lockHandle,releaseLock);
# Precondition: Cache is already connected
# Specify the key of the item
key = "Product:1001"
# Set acquireLock flag as true
acquire_lock = True
# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)
# Create a new LockHandle
lock_handle = ncache.LockHandle()
# Lock the item for a timespan of 10 seconds
item = cache.get_cacheitem(key, acquirelock=acquire_lock, locktimeout=lock_span, lockhandle=lock_handle)
# Update the value of item
product = item.get_value(Product)
product.set_units_in_stock(20)
release_lock = True
# Item is already locked with a LockHandle
# Update the item and release the lock as well since releaseLock is set to true
# Make sure that the LockHandle matches with the already added LockHandle
cache.insert(key, item, lockhandle=lock_handle, releaselock=release_lock)
// Precondition: Cache is already connected
// This is an async method
// Specify the key of the item
var key = "Product:1001";
// Set acquireLock flag as true
var acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);
// Initialize the LockHandle
var lockHandle = new ncache.LockHandle();
// cacheItemVersion set to null and readThruOptions set to null;
var item = await this.cache.getCacheItem(key,null,null, acquireLock, lockSpan, lockHandle);
// Update the value of item
var product = item.getValue(ncache.JsonDataType.Object);
product.unitsInStock = 200;
var releaseLock = true;
// Item is already locked with a LockHandle
// Update the item and release the lock as well since releaseLock is set to true
// Make sure that the LockHandle matches with the already added LockHandle
await this.cache.insert(key, item, null, lockHandle, releaseLock);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Specify the key of the item
string key = "Product:1001";
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
// Initialize the LockHandle
LockHandle lockHandle = null;
// Lock the item for 10 seconds
cache.Lock(key, TimeSpan.FromSeconds(10), out lockHandle);
// Get the item
object itemObj = cache.Get(key);
// Modify the object
product.UnitsInStock = 200;
// Item is already locked with a LockHandle
// Update the item and release the lock as well since releaseLock is set to true
// Make sure that the LockHandle matches with the already added LockHandle
cache.Insert(key, product);
명시적으로 잠금 해제
이전에 잠긴 캐시된 항목에 대한 잠금을 명시적으로 해제하려면 다음을 지정하십시오. LockHandle 처음에 해당 물품을 잠그는 데 사용되었던 것입니다. 만약 LockHandle 저장되지 않았습니다. 다른 오버로드를 사용하십시오. Unlock 항목의 잠금을 해제하는 데 키만 사용합니다.
주의 사항
유효하지 않은 경우 LockHandle 이 조건이 충족되면 예외는 발생하지 않지만 해당 항목은 잠긴 상태로 유지됩니다.
다음 예제는 이미 잠겨 있는 항목을 가져오는 방법을 보여줍니다. LockHandle그런 다음 해당 아이템을 사용하여 잠금을 해제합니다. Unlock 이전에 저장된 API를 사용합니다. LockHandle.
// Precondition: Cache is already connected
// Specify the key of the item
string key = $"Product:1001";
// Set acquireLock flag as true
bool acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Create a new LockHandle
LockHandle lockHandle = null;
Product result = cache.Get<Product>(key, acquireLock, lockSpan, ref lockHandle);
// Make sure that the item is already locked and the saved LockHandle is used
// Unlock locked item using saved LockHandle
cache.Unlock(key, lockHandle);
// Precondition: Cache is already connected
// Specify the key of the item
String key = "Product:1001";
// Set acquireLock flag as true
boolean acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
// Create a new LockHandle
LockHandle lockHandle = new LockHandle();
Object result = cache.get(key, acquireLock, lockSpan, lockHandle, Object.class);
// Make sure that the item is already locked and the saved LockHandle is used
// Unlock locked item using saved LockHandle
cache.unlock(key, lockHandle);
# Precondition: Cache is already connected
# Specify the key of the item
key = "Product:1001"
# Set acquireLock flag as true
acquire_lock = True
# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)
# Create a new LockHandle
lock_handle = ncache.LockHandle()
result = cache.get_cacheitem(key, acquirelock=acquire_lock, locktimeout=lock_span, lockhandle=lock_handle)
# Make sure that the item is already locked and the saved LockHandle is used
# Unlock locked item using saved LockHandle
cache.unlock(key, lock_handle)
// Precondition: Cache is already connected
// This is an async method
// Specify the key of the item
var key = "Product:1001";
// Set acquireLock flag as true
var acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);
// Create a new LockHandle
var lockHandle = new ncache.LockHandle();
// cacheItemVersion set to null and readThruOptions set to null;
var result = await this.cache.getCacheItem(key,null,null,acquireLock,lockSpan,lockHandle);
// Make sure that the item is already locked and the saved LockHandle is used
// Unlock locked item using saved LockHandle
await this.cache.unlock(key, lockHandle);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Specify the key of the item
string key = "Product:1001";
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockTimeout = TimeSpan.FromSeconds(10);
// Create a new LockHandle
LockHandle lockHandle = null;
// Lock the item explicitly
cache.Lock(key, lockTimeout, out lockHandle);
object item = cache.Get(key);
// Cast and use the item
Product product = item as Product;
// Release the lock
cache.Unlock(key, lockHandle);
경고
NCache 다른 오버로드가 있는 경우 잠금을 무시합니다. Get, Insert예산 및 Remove 취하거나 사용하지 않는 메소드가 호출됩니다. LockHandle.
LockHandle을 사용하여 물건을 제거하세요
Remove 메서드는 캐시에서 키를 제거하고 제거된 객체를 클라이언트로 반환하는 기본 작업입니다. 사용자 정의 객체가 캐시에 추가된 경우, Remove 메서드는 해당 객체를 반환합니다.
The LockHandle 처음에 아이템을 잠글 때 사용했던 것과 동일한 비밀번호여야 합니다. 그렇지 않으면 "아이템이 잠겨 있습니다"라는 예외 메시지가 표시됩니다.
항목이 잠겨 있지 않은 경우 LockHandle 필수 사항이 아니며, 유효성도 확인하지 않습니다.
다음 예제는 이전에 잠겨 있던 항목을 가져옵니다. LockHandle그런 다음 저장된 항목을 사용하여 캐시에서 해당 항목을 제거합니다. LockHandle 와 더불어 제거 API.
// Precondition: Cache is already connected
// Specify the key of the item
string key = $"Product:1001";
// Initialize the LockHandle
LockHandle lockHandle = null;
// Set acquireLock flag as true
bool acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Get the item using the LockHandle
Product result = cache.Get<Product>(key, acquireLock, lockSpan, ref lockHandle);
// Removing locked item using saved LockHandle
cache.Remove(key, lockHandle);
// Check if item is successfully removed
if (result != null)
{
if (result is Product)
{
Product product = (Product)result;
}
}
// Precondition: Cache is already connected
// Specify the key of the item
String key = "Product:1001";
// Create a new LockHandle
LockHandle lockHandle = new LockHandle();
// Set acquireLock flag as true
boolean acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
Object result = cache.get(key, acquireLock, lockSpan, lockHandle, Object.class);
// Removing locked item using saved LockHandle
// cacheItemVersion and writeThruOptions set to null
cache.remove(key, lockHandle, null, null, Object.class);
Object test = cache.get(key, Object.class);
// check if item has been removed
if (test != null)
{
//Item has not been removed
}
else
{
// Item has been removed
}
# Precondition: Cache is already connected
# Specify the key of the item
key = "Product:1001"
# Set acquireLock flag as true
acquire_lock = True
# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)
# Create a new LockHandle
lock_handle = ncache.LockHandle()
result = cache.get_cacheitem(key, acquirelock=acquire_lock, locktimeout=lock_span, lockhandle=lock_handle)
# Removing locked item using saved lock_handle
cache.remove(key, Product, lockhandle=lock_handle)
test = cache.get_cacheitem(key)
# Check if item has been removed
if test is not None:
# Item has not been removed
print("Remove with lock failed")
else:
# Item has been removed
print("Remove with lock successful")
// Precondition: Cache is already connected
// This is an async method
// Specify the key of the item
var key = "Product:1001";
// Set acquireLock flag as true
var acquireLock = true;
// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);
// Create a new LockHandle
var lockHandle = new ncache.LockHandle();
// CacheItemVersion and ReadThruOptions set to null
var result = await this.cache.getCacheItem(key,null,null, acquireLock, lockSpan, lockHandle, ncache.JsonDataType.Object);
// Removing locked item using saved LockHandle
// cacheItemVersion and writeThruOptions set to null
await this.cache.remove(key,ncache.JsonDataType.Object, lockHandle, null, null);
var test = await this.cache.getCacheItem(key);
// check if item has been removed
if (test != null)
{
// Item has not been removed
}
else
{
// Item has been removed
}
API 잠금 사용 시 특별 고려 사항
NCache 포함 여부에 관계없이 일련의 API를 제공합니다. LockHandle 캐시 항목을 가져오거나 업데이트합니다. 매개변수를 받지 않는 API는 다음과 같습니다. LockHandle 아이템 잠금을 무시하세요. 따라서 모든 잠금 API는 데이터 조작에 사용해야 합니다. 예를 들어, 아이템이 잠겨 있고 잠금이 필요하지 않은 업데이트 API를 호출하는 경우 LockHandle 입력 매개변수로 지정하면 해당 항목의 잠금 상태와 관계없이 캐시에서 해당 항목이 업데이트됩니다.
중대한
잠금 기능을 사용할 때는 다음을 수행하는 API 호출만 사용해야 합니다. LockHandle 매개변수로 사용합니다. 매개변수를 받지 않는 API는 다음과 같습니다. LockHandle 데이터 무결성에 영향을 미치지 않도록 매우 주의해서 사용해야 하지만, 여전히 사용할 수 있습니다.
주의 사항
퇴거/만료의 경우, NCache 잠금을 무시합니다. 즉, 잠긴 항목도 만료 또는 강제 퇴거로 인해 제거될 수 있습니다.
분산 캐시 토폴로지 전반에 걸친 잠금 동작
. 복제 토폴로지에서 클라이언트는 하나의 노드에 연결됩니다. 모든 잠금 작업에 대해 LockHandle 클라이언트 요청을 수신하는 노드에서 생성되고, 그 후 동일한 내용이 반복됩니다. LockHandle 데이터 일관성을 위해 다른 모든 노드에 복제됩니다. 마찬가지로 잠금 해제 작업도 다른 모든 노드에 복제됩니다.
. 파티션 된 토폴로지, LockHandle 해당 아이템을 포함하는 노드와 동일한 노드에서 생성되고 존재합니다. 상태 전송 중에 LockHandle 항목이 다른 노드로 이동하는 경우에도 정보도 항목과 함께 전송됩니다.
. 파티션-복제본 토폴로지, LockHandle 해당 아이템을 포함하는 활성 노드에서 생성되며, 동일한 LockHandle 그런 다음 데이터 일관성을 보장하기 위해 복제본으로 복제됩니다. 상태 전송 중에 LockHandle 항목이 다른 노드로 이동하는 경우에도 정보도 항목과 함께 전송됩니다.
. 클라이언트 캐시 토폴로지 측면에서 모든 락 기반 작업은 클러스터형 캐시에서 직접 수행됩니다. 즉, LockHandle 클러스터형 캐시에 생성되어 저장됩니다. 클라이언트 캐시에는 잠금 관련 정보가 유지되지 않습니다.
추가 자료
NCache 항목 잠금에 대한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.런타임.캐싱 네임 스페이스.
자바 : com.alachisoft.ncache.런타임.캐싱 네임 스페이스.
파이썬 : ncache.런타임.캐싱 기준 치수.
Node.js : 캐시 클래스입니다.