• Facebook
  • 트위터
  • 유튜브
  • 라인드인
  • RSS
  • 기술 문서
  • 비교
  • 블로그
  • 다운로드
  • 문의하기
다운로드
목차 표시/숨기기

캐시의 대기열 동작 및 사용량

큐는 선입선출(FIFO) 원칙을 따르는 정렬된 데이터 구조입니다. NCache 분산 큐를 사용하면 여러 애플리케이션 인스턴스에서 높은 일관성을 유지하면서 항목을 대기열에 넣고 꺼낼 수 있습니다. 대량 작업 및 이벤트 알림을 기본적으로 지원합니다. NCache Queue 데이터 구조를 더욱 향상시켜 다음을 제공합니다. NCache-다음과 같은 특정 기능 그룹, 태그, 만료, 잠금, 종속성수록.

큐를 사용할 수 있습니다. NCache 실행 중에 처리되는 정보를 유지하기 위해 사용됩니다. 예를 들어, 회사 지원자들의 지원 ID를 큐에 저장할 수 있습니다. 큐는 선입선출(FIFO) 방식이므로, 먼저 지원한 지원자가 먼저 면접을 보게 됩니다. 또한, 회사는 관리직 지원자들을 위한 그룹을 지정하여 큐를 관리할 수도 있습니다.

NCache 분산 큐 동작

  • 큐는 모든 기본 유형이나 사용자 정의 객체가 될 수 있습니다.
  • 대기열 CacheItem 중첩 대기열은 아직 지원되지 않습니다.
  • 큐에는 이름이 지정되어 있습니다. 따라서 각 큐마다 고유한 캐시 키를 제공해야 합니다.
  • null 값은 지원되지 않습니다.
  • 중복 값이 ​​지원됩니다.

사전 조건

사용하기 전에 NCache 클라이언트 측 API를 사용할 때 다음 전제 조건을 충족하는지 확인하십시오.

  • . NET
  • 자바
  • Node.js를
  • .NET 클라이언트 애플리케이션에 다음 NuGet 패키지를 설치하세요.
    • 기업: Alachisoft.NCache.SDK
    • 오픈 소스: Alachisoft.NCache오픈소스 SDK
  • 애플리케이션에 다음 네임스페이스를 포함합니다.
    • Alachisoft.NCache.고객
    • Alachisoft.NCache.런타임.예외
    • Alachisoft.NCache.클라이언트.데이터 유형
    • Alachisoft.NCache.Client.DataTypes.Collections
    • Alachisoft.NCache.런타임.캐싱
    • Alachisoft.NCache.런타임.이벤트
  • 캐시가 실행 중이어야 합니다.
  • 추가되는 데이터가 직렬화 가능.
  • API 세부 정보는 다음을 참조하세요. 아이캐시, IDistributedQueue, IDataTypeManager, 포함, 에게 복사, 배열로, 몰래 엿보기, 큐 가져오기, 대기열에서 빼기, 대기열에 넣기, EnqueueBulk, DequeueBulk, 큐 생성, 등록 알림, 데이터 유형 데이터 알림 콜백, 이벤트 유형, 데이터 유형 이벤트 데이터 필터, 로크, 자물쇠를 열다, 데이터 유형 관리자, 데이터 유형 이벤트 인수.
  • Java 클라이언트 애플리케이션에 대해 다음 Maven 종속성을 추가합니다. pom.xml 파일 :
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache Enterprise-->
    <artifactId>ncache-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Java 클라이언트 애플리케이션에서 다음 패키지를 가져옵니다.
    • import **클라이언트 이름**
    • import com.alachisoft.ncache.런타임.예외.*;
    • import com.alachisoft.ncache.client.데이터 구조.*;
    • import com.alachisoft.ncache.runtime.events.*;
    • import com.alachisoft.ncache.runtime.dependencies.*;
  • 캐시가 실행 중이어야 합니다.
  • 추가되는 데이터가 직렬화 가능.
  • API 세부 정보는 다음을 참조하세요. 캐시, 분산 큐, 큐 만들기, getQueue, 자물쇠, 잠금을 해제, 이벤트 유형, 이벤트 유형, addChangeListener, getDataStructuresManager, onDataStructure변경됨, 데이터 유형 이벤트 데이터 필터, DataStructureDataChangeListener, DataStructureEventArg, getCollection항목, 에게 복사, 몰래 엿보다, toArray.
  • Node.js 클라이언트 애플리케이션에 다음 모듈을 설치하고 포함시키세요.

    • 기업: ncache-클라이언트
  • 애플리케이션에 다음 클래스를 포함합니다.

    • 캐시
    • 데이터 구조 관리자
    • 분산 큐
  • 캐시가 실행 중이어야 합니다.
  • 추가되는 데이터가 직렬화 가능.
  • API 세부 정보는 다음을 참조하세요. 캐시, 분산 큐, getDataStructuresManager, 큐 만들기, 더하다, getQueue, 이 포함되어 있습니다, 에게 복사, toArray, 몰래 엿보다, 제거, 이벤트 유형, DataStructureDataChangeListener, addChangeListener, 데이터 유형 이벤트 데이터 필터, DataStructureEventArg, 이벤트 유형, getCollection항목.

대기열을 만들고 데이터를 추가하는 방법

다음 코드 예제는 큐를 생성하는 방법을 보여줍니다. 후보자 캐시 키에 대해 캐시에 유형을 입력합니다. 후보자 대기열 및 항목이 대기열에 추가되는 방법.

팁

당신은 또한 수 검색 가능한 속성 구성 그룹/태그/명명된 태그와 같은 무효화 속성 데이터 구조를 생성하는 동안 만료/퇴거/종속성과 같은.

  • . NET
  • 자바
  • Node.js를
try
{
  // Precondition: Cache is already connected

  // Specify unique cache key for Queue
  string key = "CandidateQueue";

  // Create Queue of Candidate type
  IDistributedQueue<Candidate> queue = cache.DataTypeManager.CreateQueue<Candidate>(key);

  Candidate[] candidates = FetchCandidates();

  foreach(var candidate in candidates)
  {
      // Add candidates to Queue
      queue.Enqueue(candidate);
  }
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
    {
        // The specified key already exists in cache,
        // Either remove the existing object from cache
        // Or specify another key
    }
    else if (ex.ErrorCode == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES)
    {
        // Data structures cannot be of CacheItem type
        // CacheItems cannot be added in data structures
    }
    else
    {
        // NCache specific exception
        // 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

  // Specify unique cache key for Queue
  String key = "CandidateQueue";

  // Create Queue of Candidate type
  DistributedQueue<Candidate> queue = cache.getDataStructuresManager().createQueue(key, Candidate.class);

  Candidate[] candidates = fetchCandidates();

  for (var candidate : candidates)
  {
      // Add candidates to Queue
      queue.add(candidate);
  }
}
catch (OperationFailedException ex) 
{
    if (ex.getErrorCode() == NCacheErrorCodes.KEY_ALREADY_EXISTS) {
        // The specified key already exists in cache,
        // Either remove the existing object from cache
        // Or specify another key
    } else if (ex.getErrorCode() == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES) {
        // Data structures cannot be of CacheItem type
        // CacheItems cannot be added in data structures
    } else {
        // 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
{
  // This is an async method
  // Precondition: Cache is already connected

  // Specify unique cache key for Queue
  var key = "CandidateQueue";

  // Create Queue
  var manager = await this.cache.getDataStructuresManager();
  var queue = await manager.createQueue(key, ncache.JsonDataType.Object);

  var candidates = this.fetchCandidates();
  for (var candidate in candidates) 
  {
  // Add candidates to Queue
  queue.add(candidate);
  }
}
catch (error) {
  // Handle errors
}

대기열을 생성하고 데이터를 일괄 추가하는 방법

단일 호출에서 여러 항목을 추가하려면 다음을 사용할 수 있습니다. EnqueueBulk 방법. 다음 코드 샘플은 Queue의 방법을 보여줍니다. 후보자 유형은 캐시 키에 대해 캐시에서 생성될 수 있습니다. 후보자 대기열 그리고 여러 항목을 대량으로 대기열에 추가하는 방법도 있습니다.

주의 사항

The EnqueueBulk 이 방법은 제공된 목록에 나타나는 것과 같은 순서로 항목이 추가되도록 보장합니다.

  • . NET
// Precondition: Cache is already connected

// Specify unique cache key for queue
string key = "CandidateQueue";

// Create Queue of Candidate type
IDistributedQueue<Candidate> queue = cache.DataTypeManager.CreateQueue<Candidate>(key);
Candidate[] candidates = FetchCandidates();

// Add a list of candidates to the queue
queue.EnqueueBulk(candidates);

항목을 추가하는 동안 오류가 발생하는 경우 EnqueueBulk 작업이 완료되면 전체 프로세스가 롤백됩니다. 사용자는 모든 항목을 대기열에 추가하거나, 항목이 추가되지 않고 예외가 발생합니다.

큐에서 데이터를 가져오고 다른 메서드를 실행하는 방법

다음 코드 샘플은 다음을 사용하여 캐시에서 Queue를 가져옵니다. GetQueue 해당 메서드를 사용한 다음, 큐에 항목이 존재하는지 여부를 확인합니다. Contains 이 메서드는 큐에서 항목을 제거하지 않고 큐의 시작 부분에서 항목을 가져옵니다. Peek 이 방법을 사용하면 소스 큐 전체를 대상 배열로 복사할 수 있습니다. CopyTo 해당 방법을 사용하여 1차원 배열로 변환합니다. ToArray 방법.

  • . NET
  • 자바
  • Node.js를
// Precondition: Cache is already connected

// Queue with this key already exists in cache
string key = "CandidateQueue";

// Get Queue and show items of Queue
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);

// Get any candidate ID
Candidate candidate = GetCandidateByID(1002);

// Check whether Queue contains the particular candidate or not
if (retrievedQueue.Contains(candidate))
{
    // Candidate exists with this ID
}
// List of candidates for the Queue to be copied into
Candidate[] candidates = new Candidate[retrievedQueue.Count];

// Copy the Queue to another array
retrievedQueue.CopyTo(candidates, 0);

// Copy Queue to one-dimensional array
candidates = retrievedQueue.ToArray();

// Get an item at beginning from Queue without removing
Candidate firstCandidate = retrievedQueue.Peek();
// Precondition: Cache is already connected

// Queue with this key already exists in cache
String key = "CandidateQueue";

// Get Queue and show items of Queue
DistributedQueue<Candidate> retrievedQueue = cache.getDataStructuresManager().getQueue(key, Candidate.class);

// Get any candidate ID
Candidate candidate = getCandidateByID(1002);

// Check whether Queue contains the particular candidate or not
if (retrievedQueue.contains(candidate))
{
    // Candidate exists with this ID
}

// List of candidates for the Queue to be copied into
Candidate[] candidates = new Candidate[retrievedQueue.size()];

// Copy the Queue to another array
retrievedQueue.copyTo(candidates, 0);

// Copy Queue to one-dimensional array
candidates = retrievedQueue.toArray(new Candidate[0]);

// Get an item from the beginning of the queue without removing it
Candidate firstCandidate = retrievedQueue.peek();
// Precondition: Cache is already connected
// This is an async method

// Queue with this key already exists in cache
var key = "CandidateQueue";

// Get Queue and show items of Queue
var manager = await this.cache.getDataStructuresManager();
var retrievedQueue = await manager.getQueue(key, ncache.JsonDataType.Object);

// Get any candidate ID
var candidate = this.getCandidateByID(1002);

// Check whether Queue contains the particular candidate or not
if (retrievedQueue.contains(candidate))
{
// Candidate exists with this ID
}

// List of candidates
var candidates = await retrievedQueue.toArray();

// Get an item from the beginning of the queue without removing it
var firstCandidate = await retrievedQueue.peek();

대기열에서 항목을 제거하는 방법

항목은 FIFO 방식으로 큐에서 제거될 수 있습니다. 다음 코드 샘플은 큐에서 첫 번째 후보를 제거합니다.

팁

캐시에서 전체 대기열을 제거하려면 다음을 참조하세요. 캐시에서 데이터 구조 제거 페이지를 확인하시기 바랍니다.

  • . NET
  • 자바
  • Node.js를
// Precondition: Cache is already connected

// Queue with this key already exists in cache
string key = "CandidateQueue";
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);

// Remove the first item of the queue
retrievedQueue.Dequeue();
// Precondition: Cache is already connected

// Queue with this key already exists in cache
String key = "CandidateQueue";
DistributedQueue<Candidate> retrievedQueue = cache.getDataStructuresManager().getQueue(key, Candidate.class);

// Remove the first item of the queue
retrievedQueue.remove();
// Precondition: Cache is already connected

// This is an async method
// Queue with this key already exists in cache
var key = "CandidateQueue";
var manager = await this.cache.getDataStructuresManager();
var retrievedQueue = await manager.getQueue(key, ncache.JsonDataType.Object);

// Remove the first item of the queue
await retrievedQueue.remove();
주의 사항

작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.

데이터를 일괄 삭제하는 방법

단일 호출에서 여러 항목을 제거하려면 다음을 사용할 수 있습니다. DequeueBulk 방법. 그만큼 DequeueBulk 방법은 maxItems 큐에서 제거할 최대 항목 수를 지정하는 매개변수입니다. 큐에 지정된 개수보다 적은 항목이 있는 경우, 사용 가능한 항목만 큐에서 제거됩니다. 예를 들어, 10을 지정했지만 항목이 7개만 있는 경우, 7개 항목이 모두 큐에서 제거됩니다. 최대 항목 수의 기본값은 10입니다.

다음 코드 샘플은 Queue를 가져오는 방법을 보여줍니다. 후보자 캐시 키를 사용하여 입력 후보자 대기열 그리고 여러 항목을 대량으로 대기열에서 제거하는 방법.

주의 사항

The DequeueBulk 이 방법은 지정된 개수까지 항목이 추가된 순서대로 대기열에서 제거되도록 보장합니다.

경고

를 사용할 때 DequeueBulk 이 방법을 사용할 때는 해당 시점에 처리에 필요한 항목 수만큼만 큐에서 꺼내는 것이 좋습니다. 필요 이상으로 많은 항목을 꺼내면 각 작업마다 처리 비용이 발생하기 때문에 처리 시간이 증가할 수 있으며, 특히 큐에 저장된 데이터 양이 많을 경우 더욱 그렇습니다.

  • . NET
// Precondition: Cache is already connected

// Queue with this key already exists in cache
string key = "CandidateQueue";
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);

// Remove at most the first 10 items in the Queue
IList<Candidate> dequeuedItems = retrievedQueue.DequeueBulk(10);
주의 사항

대기열이 비어 있는 경우 DequeueBulk 작업을 수행하면 예외가 발생합니다.

유사하게 EnqueueBulk, 항목을 제거하는 동안 오류가 발생하는 경우 DequeueBulk 작업이 완료되면 전체 프로세스가 롤백됩니다. 사용자는 요청된 모든 항목을 수신하거나, 항목이 반환되지 않고 예외가 발생합니다.

큐에 이벤트 알림 등록하기

Queue와 같은 데이터 구조에 캐시 이벤트, 키 기반 이벤트 및 데이터 구조 이벤트를 등록할 수 있습니다. 자세한 내용은 다음을 참조하세요. 기능별 동작.

큐에 생성된 이벤트를 등록하는 방법

다음 코드 예제는 큐에 데이터 구조 이벤트 알림을 등록합니다. .NET 예제는 다음과 같이 등록합니다. ItemAdded, ItemUpdated예산 및 ItemRemoved Java 및 Node.js 예제는 ItemAdded 및 ItemRemoved 이벤트를 등록하는 반면, ItemAdded 및 ItemRemoved 이벤트는 등록합니다. 큐를 생성하면 이벤트가 트리거됩니다. ItemAdded 캐시 수준 이벤트가 발생하는 반면, 기존 큐에 항목을 추가하면 다른 이벤트가 발생합니다. ItemAdded 데이터 구조 이벤트 및 ItemUpdated 캐시 레벨 이벤트.

  • . NET
  • 자바
  • Node.js를
// Precondition: Cache is already connected

// Unique cache key for Queue
string key = "CandidateQueue";

// Create Queue of Candidate type
IDistributedQueue<Candidate> queue = cache.DataTypeManager.CreateQueue<Candidate>(key);

// Register ItemAdded, ItemUpdated, ItemRemoved events on Queue created
// DataTypeNotificationCallback is callback method specified
queue.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
        EventType.ItemUpdated | EventType.ItemRemoved,
        DataTypeEventDataFilter.Data);

// Perform operations
// Precondition: Cache is already connected

// Unique cache key for the Queue
String key = "CandidateQueue";

// Create Queue of candidate type
DistributedQueue<Candidate> queue = cache.getDataStructuresManager().createQueue(key, Candidate.class);

// Create EnumSet of event types
EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemAdded, EventType.ItemRemoved);

// Register ItemAdded and ItemRemoved events on the created Queue
// dataChangeListener is the specified callback method
queue.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data);

// Perform operations
// Precondition: Cache is already connected

// This is an async method
// Unique cache key for the Queue
var key = "CandidateQueue";

// Create Queue of candidate type
var manager = await this.cache.getDataStructuresManager();
var queue = await manager.createQueue(key, ncache.JsonDataType.Object);

// Create EnumSet of event types
// Update EventType is not supported
var enumSet = [
ncache.EventType.ItemAdded,
ncache.EventType.ItemRemoved
];

queue.addChangeListener(
this.dataStructureListener, // Make sure this is initialized
enumSet,
ncache.DataTypeEventDataFilter.Data
);

// Perform operations

이벤트 알림에 대한 콜백 함수 지정 방법

다음 코드 샘플은 컬렉션에서 항목이 추가, 업데이트 또는 제거될 때와 같이 다양한 이벤트에 대한 알림을 수신하기 위한 콜백 메서드를 지정하는 방법을 보여줍니다. 이러한 이벤트를 처리함으로써 캐시 내의 변경 사항에 대한 응답으로 특정 작업을 트리거할 수 있습니다.

  • . NET
  • 자바
  • Node.js를
private void DataTypeDataNotificationCallback(string collectionName, DataTypeEventArg collectionEventArgs)
{
    switch (collectionEventArgs.EventType)
    {
        case EventType.ItemAdded:
            // Item has been added to the collection
        break;
        case EventType.ItemUpdated:
            if (collectionEventArgs.CollectionItem != null)
            {
                // Item has been updated in the collection
                // Perform operations
            }
        break;
        case EventType.ItemRemoved:
            // Item has been removed from the collection
        break;
    }
}
public DataStructureDataChangeListener dataStructureListener = new DataStructureDataChangeListener() {
    @Override
    public void onDataStructureChanged(String collection, DataStructureEventArg dataStructureEventArg) {
        switch (dataStructureEventArg.getEventType()) {
            case ItemAdded:
                // Item has been added to the collection
            break;

            case ItemRemoved:
                //Item has been removed from the collection
            break;
        }
    }
};
// Update event is not supported for this dataType
onDataStructureChanged(collectionName, eventArg)
{
  switch (eventArg.getEventType())
  {
    case ncache.EventType.ItemAdded:
      // Item has been added to the collection
      break;

    case ncache.EventType.ItemRemoved:
      // Item has been removed from the collection
      break;
  }
}

대기열을 잠그는 방법

데이터 일관성을 보장하기 위해 대기열을 명시적으로 잠그거나 잠금 해제할 수 있습니다. 다음 코드 샘플은 대기열을 생성하고 10초 동안 잠급니다. 로크 그런 다음 사용하여 잠금을 해제합니다. 자물쇠를 열다.

  • . NET
  • 자바
// Precondition: Cache is already connected

// Queue exists with key "CandidateQueue" cache key
string key = "CandidateQueue";

// Get Queue
IDistributedQueue<Candidate> queue = cache.DataTypeManager.GetQueue<Candidate>(key);

// Lock Queue for 10 seconds
bool isLocked = queue.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
    // Queue is successfully locked for 10 seconds
    // Unless explicitly unlocked
}
else
{
    // Queue is not locked because either:
    // Queue is not present in the cache
    // Queue is already locked
}

queue.Unlock();
// Precondition: Cache is already connected

// Queue exists with key "CandidateQueue" cache key
String key = "CandidateQueue";

// Get Queue
DistributedQueue<Candidate> queue = cache.getDataStructuresManager().getQueue(key, Candidate.class);

// Lock Queue for 10 seconds
boolean isLocked = queue.lock(TimeSpan.FromSeconds(10));

if (isLocked)
{
    // Queue is successfully locked for 10 seconds
    // Unless explicitly unlocked
} else
{
    // Queue is not locked because either:
    // Queue is not present in the cache
    // Queue is already locked
}
queue.unlock();

추가 자료

NCache Queue 데이터 구조에 대한 샘플 애플리케이션을 제공합니다. GitHub의.

도 참조

.그물: Alachisoft.NCache.클라이언트.데이터 유형 네임 스페이스.
자바 : com.alachisoft.ncache.client.데이터 구조 네임 스페이스.
Node.js : 분산 큐 클래스입니다.

문의하기

전화

+1 214-619-2601   (미국)

+44 20 7993 8327   (UK)

 
이메일

sales@alachisoft.com

support@alachisoft.com

NCache
  • 판 비교
  • NCache 아키텍처
  • 벤치 마크
다운로드
가격
놀이터를 사용해보십시오

배포
  • 클라우드(SaaS 및 소프트웨어)
  • 온 프레미스
  • Kubernetes
  • 도커
기술 사용 사례
  • ASP.NET 세션
  • ASP.NET 코어 세션
  • 게시/구독 메시징
  • 실시간 ASP.NET SignalR
  • 사물의 인터넷 IOT ()
  • NoSQL 데이터베이스
  • 스트림 처리
  • 마이크로 서비스
리소스
  • 잡지 기사
  • 제XNUMX자 기사
  • 기사
  • 비디오
  • 백서
  • 쇼
  • 회담
  • 블로그
  • 기술 문서
고객 사례 연구
  • 환자 후기
  • 고객
고객 지원
  • 데모 예약
  • 포럼(Google 그룹스)
  • Tips
회사
  • Leadership
  • 파트너
  • ​뉴스
  • 이벤트
  • 채용 정보
문의하기

  • 영어중국어 (간체)프랑스어독일 사람이탈리아 사람일본제한국어포르투갈어스페인어

  • 문의하기
  •  
  • 사이트 맵
  •  
  • 이용 약관
  •  
  • 개인정보 처리방침
© 저작권 Alachisoft 2002 - . 판권 소유. NCache 는 Diyatech Corp.의 등록상표입니다.
맨 위로