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

캐시의 동작 및 사용 설정

HashSet은 중복 값을 허용하지 않는 순서가 없는 데이터 구조입니다. 예를 들어, HashSet을 사용하여 특정 날짜에 전자상거래 사이트에 로그인하는 모든 사용자의 사용자 ID를 저장할 수 있습니다. 사용자가 다시 로그인하는 경우, 중복 값이 ​​허용되지 않으므로 해당 ID는 저장되지 않습니다. 로컬 HashSet과 달리, NCache 이 구현을 통해 전체 컬렉션을 클라이언트로 가져오지 않고도 캐시 클러스터에서 직접 집합 연산(합집합, 교집합, 차집합)을 수행할 수 있으므로 대규모 데이터 세트에 대해 높은 성능을 보장합니다.

NCache 제공하여 HashSet을 더욱 향상시킵니다. NCache 다음과 같은 특정 기능 그룹, 태그, 만료, 잠금, 종속성수록.

행동

  • HashSet은 기본 유형만 될 수 있습니다.
  • HashSets의 이름이 지정됩니다. 따라서 각 HashSet에 대해 고유한 캐시 키를 제공해야 합니다.
  • Null은 지원되는 값 유형이 아닙니다.
  • 중복 값은 지원되지 않습니다.

사전 조건

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

  • . NET
  • 자바
  • .NET 클라이언트 애플리케이션에 다음 NuGet 패키지를 설치하세요.
    • 기업: Alachisoft.NCache.SDK
    • 오픈 소스: Alachisoft.NCache오픈소스 SDK
  • 애플리케이션에 다음 네임스페이스를 포함합니다.
    • Alachisoft.NCache.고객
    • Alachisoft.NCache.런타임.예외
    • Alachisoft.NCache.클라이언트.데이터 유형
    • Alachisoft.NCache.Client.DataTypes.Collections
    • Alachisoft.NCache.런타임.캐싱
    • Alachisoft.NCache.런타임.이벤트
  • 캐시가 실행 중이어야 합니다.
  • 추가되는 데이터가 직렬화 가능.
  • API 세부 정보는 다음을 참조하세요. 아이캐시, IDistributedHashSet, IDataTypeManager, CreateHashSet, GetHashSet, 스토어 유니온, 상점 교차로, 스토어차이, 제거, 등록 알림, 데이터 유형 데이터 알림 콜백, 이벤트 유형, 데이터 유형 이벤트 데이터 필터, 로크, 자물쇠를 열다, 데이터 유형 관리자, 데이터 유형 이벤트 인수.
  • 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 세부 정보는 다음을 참조하세요. 캐시, 분산해시세트, getDataStructuresManager, createHashSet, getHashSet, 스토어 유니온, 상점 교차로, 매장차이, 이벤트 유형, 이벤트 유형, DataStructureDataChangeListener, onDataStructure변경됨, DataStructureEventArg, 데이터 유형 이벤트 데이터 필터, getCollection항목, 자물쇠, 잠금을 해제, addChangeListener, 제거.

HashSet 생성 및 데이터 추가

주의 사항

집합에는 중복된 값이 포함될 수 없습니다.

다음 코드 샘플은 다음을 사용하여 캐시에 int 유형의 HashSet 두 개를 생성합니다. CreateHashSet 월요일과 화요일에 로그인하는 사용자의 경우. 그런 다음 이 두 HashSet에 데이터를 추가합니다.

팁

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

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

  // Create unique keys for HashSets
  string mondayUsersKey = "MondayUsers";
  string tuesdayUsersKey = "TuesdayUsers";

  // Create HashSets of int type
  IDistributedHashSet<int> userSetMonday = cache.DataTypeManager.CreateHashSet<int>(mondayUsersKey);

  // Add user IDs for Monday
  userSetMonday.Add(1223);
  userSetMonday.Add(34564);
  userSetMonday.Add(3564);
  IDistributedHashSet<int> userSetTuesday = cache.DataTypeManager.CreateHashSet<int>(tuesdayUsersKey);

  // Add userIDs for Tuesday
  userSetTuesday.Add(4545);
  userSetTuesday.Add(34564);
  userSetTuesday.Add(3564);
  userSetTuesday.Add(7879);
}
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
    {
        // 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

  // Create unique keys for HashSets
  String mondayUsersKey = "MondayUsers";
  String tuesdayUsersKey = "TuesdayUsers";

  // Create HashSets of int type
  DistributedHashSet userSetMonday = cache.getDataStructuresManager().createHashSet(mondayUsersKey, Integer.class);

  // Add user IDs for Monday
  userSetMonday.add(1223);
  userSetMonday.add(34564);
  userSetMonday.add(3564);
  DistributedHashSet userSetTuesday = cache.getDataStructuresManager().createHashSet(tuesdayUsersKey, Integer.class);

  // Add userIDs for Tuesday
  userSetTuesday.add(4545);
  userSetTuesday.add(34564);
  userSetTuesday.add(3564);
  userSetTuesday.add(7879);
}
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
}
주의 사항

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

HashSets에서 합집합과 교집합 수행

NCache 또한 다음과 같은 기본 HashSet 작업에 대한 지원을 제공합니다. Union, Intersection예산 및 Difference. 다음 코드 예제에서는 데이터를 저장하는 int 유형의 HashSet 세 개를 만듭니다. Union, Intersection예산 및 Difference 두 개의 HashSet 중 userSet월요일 userSet화요일 이전 예에서 생성:

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

// Create unique keys for HashSets
string totalUsersKey = "TotalUsers";
string weeklyUsersKey = "WeeklyUsers";
string differenceKey = "Difference";

// Create HashSets of int type
IDistributedHashSet<int> userSetTotal = cache.DataTypeManager.CreateHashSet<int>(totalUsersKey);
IDistributedHashSet<int> userSetWeekly = cache.DataTypeManager.CreateHashSet<int>(weeklyUsersKey);
IDistributedHashSet<int> userSetDifference = cache.DataTypeManager.CreateHashSet<int>(differenceKey);

// userSetTotal will contain unique values from the HashSets userSetMonday and userSetTuesday after union
userSetMonday.StoreUnion(totalUsersKey, tuesdayUsersKey);

// userSetWeekly will contain common values from the HashSets userSetMonday and userSetTuesday after intersection
userSetMonday.StoreIntersection(weeklyUsersKey, tuesdayUsersKey);

// userSetDifference will contain the difference between the HashSets userSetMonday and userSetTuesday
userSetMonday.StoreDifference(differenceKey, tuesdayUsersKey);
// Precondition: Cache is already connected

// Create unique keys for HashSets
String totalUsersKey = "TotalUsers";
String weeklyUsersKey = "WeeklyUsers";
String differenceKey = "Difference";

// Create HashSets of int type
DistributedHashSet userSetTotal = cache.getDataStructuresManager().createHashSet(totalUsersKey, Integer.class);
DistributedHashSet userSetWeekly = cache.getDataStructuresManager().createHashSet(weeklyUsersKey, Integer.class);
DistributedHashSet userSetDifference = cache.getDataStructuresManager().createHashSet(differenceKey, Integer.class);

// userSetTotal will contain unique values from the HashSets userSetMonday and userSetTuesday after union
userSetMonday.storeUnion(totalUsersKey, tuesdayUsersKey);

// userSetWeekly will contain common values from the HashSets userSetMonday and userSetTuesday after intersection
userSetMonday.storeIntersection(weeklyUsersKey, tuesdayUsersKey);

// userSetDifference will contain the difference between the HashSets userSetMonday and userSetTuesday
userSetMonday.storeDifference(differenceKey, tuesdayUsersKey);

캐시에서 HashSet 가져오기

다음을 사용하여 캐시에서 HashSet을 가져올 수 있습니다. GetHashSet 캐시 키를 매개변수로 사용합니다. 이 키는 HashSet 생성 중에 지정되는 HashSet의 이름입니다.

경고

가져오는 항목이 HashSet 유형이 아닌 경우 Type mismatch 예외가 발생합니다.

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

// HashSet with this key already exists in cache
string key = "ProductIDSet";

// Get HashSet and show items of HashSet
IDistributedHashSet<int> retrievedHashSet = cache.DataTypeManager.GetHashSet<int>(key);
if (retrievedHashSet != null)
{
    foreach (var item in retrievedHashSet)
    {
        // Perform operations
    }
}
else
{
    // HashSet does not exist
}
// Precondition: Cache is already connected

// HashSet with this key already exists in cache
String key = "ProductIDSet";

// Get HashSet and show items of HashSet
DistributedHashSet retrievedHashSet = cache.getDataStructuresManager().getHashSet(key, Integer.class);
if (retrievedHashSet != null) 
{
    for (var item : retrievedHashSet) 
    {
        // Perform operations
    }
} else
{
    // HashSet does not exist
}

HashSet에서 항목 제거

항목 자체를 지정하거나 임의로 HashSet에서 항목을 제거할 수 있습니다. 다음 코드 샘플은 주간 사용자 HashSet(이미 캐시에 추가됨)에서 Monday 사용자를 제거합니다.

팁

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

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

// Get existing HashSets
string userIDMondayKey = "UserIDMonday";
string userIDWeeklyKey = "UserIDWeekly";
IDistributedHashSet<int> userSetMonday = cache.DataTypeManager.GetHashSet<int>(userIDMondayKey);
IDistributedHashSet<int> usersWeekly = cache.DataTypeManager.GetHashSet<int>(userIDWeeklyKey);

// Remove users of Monday from Weekly HashSet
var removedItem = usersWeekly.Remove(userSetMonday);
// Precondition: Cache must be connected

// Get existing HashSets
String userIDMondayKey = "UserIDMonday";
String userIDWeeklyKey = "UserIDWeekly";
DistributedHashSet userSetMonday = cache.getDataStructuresManager().getHashSet(userIDMondayKey, Integer.class);
DistributedHashSet usersWeekly = cache.getDataStructuresManager().getHashSet(userIDWeeklyKey, Integer.class);

// Remove users of Monday from Weekly HashSet
var removedItem = usersWeekly.remove(userSetMonday);

HashSet의 이벤트 알림

HashSet과 같은 데이터 구조에 캐시 이벤트, 키 기반 이벤트 및 데이터 구조 이벤트를 등록할 수 있습니다. 행동에 대해서는 다음을 참조하십시오. 특징적인 행동.

다음 코드 예제는 HashSet에 데이터 구조 이벤트 알림을 등록합니다. .NET 예제는 다음과 같이 등록합니다. ItemAdded, ItemUpdated예산 및 ItemRemoved 이벤트가 발생하지만 Java 예제는 등록합니다. ItemAdded ItemRemoved 이벤트. HashSet을 생성하면 이벤트가 발생합니다. ItemAdded 캐시 레벨 이벤트입니다. 기존 HashSet에 항목을 추가하면 이 이벤트가 발생합니다. ItemAdded 데이터 구조 이벤트 및 ItemUpdated 캐시 레벨 이벤트.

생성된 HashSet에 이벤트 등록

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

// Unique cache key for hashset
string key = "UserIDMonday";

// Create hashset
IDistributedHashSet<int> hashset = cache.DataTypeManager.CreateHashSet<int>(key);

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

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

// Unique cache key for hashset
String key = "UserIDMonday";

// Create HashSet
DistributedHashSet<Integer> hashSet = cache.getDataStructuresManager().createHashSet(key, Integer.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 HashSet created, ItemUpdated event is not supported for this data type
// dataChangeListener is the specified callback method
hashSet.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data);

// Perform operations

이벤트 알림에 대한 콜백 지정

  • . NET
  • 자바
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;
    }
}
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;
        }
    }
};

HashSet 잠금

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

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

// HashSet exists with key "UserIDMonday" Cache Key
string key = "UserIDMonday";

// Get HashSet
IDistributedHashSet<int> hashset = cache.DataTypeManager.GetHashSet<int>(key);

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

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

// HashSet exists with key "UserIDMonday" Cache Key
String key = "UserIDMonday";

// Get HashSet
DistributedHashSet hashset = cache.getDataStructuresManager().getHashSet(key, Integer.class);

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

추가 자료

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

도 참조

.그물: Alachisoft.NCache.클라이언트.데이터 유형 네임 스페이스.
자바 : com.alachisoft.ncache.client.데이터 구조 네임 스페이스.

문의하기

전화

+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.의 등록상표입니다.
맨 위로