SQL/NoSQL 데이터베이스와 캐시 동기화

NCache SQL Server, Oracle 및 NoSQL 데이터베이스와 분산 캐시를 자동으로 동기화하여 실시간 데이터 일관성을 제공합니다. 이를 통해 애플리케이션은 항상 최신 데이터를 밀리초 미만의 성능으로 제공하고, 이벤트 기반 알림 및 폴링을 통해 오래된 데이터를 제거합니다.

NCache 애플리케이션 데이터를 캐싱하여 애플리케이션 성능을 향상시킬 수 있는 매우 빠르고 선형적으로 확장 가능한 분산 캐시입니다. 애플리케이션 데이터를 캐싱하면 데이터베이스에도 존재하는 캐시의 데이터 복사본이 생성됩니다. 데이터베이스의 데이터가 변경되면 캐시도 업데이트되어 항상 데이터베이스와 일관성을 유지해야 합니다.

이 상황을 처리하기 위해, NCache 이 소프트웨어는 관계형 또는 NoSQL 데이터베이스의 데이터가 변경될 때 캐시가 자체적으로 동기화되는 강력한 데이터베이스 동기화 기능을 제공합니다. 여기서 동기화란 해당 캐시 항목을 캐시에서 제거하거나(또는 다시 로드하는 것)을 의미합니다. 전체 읽기). NCache 데이터베이스 동기화를 위해 다음을 제공합니다.

  1. SQL 종속성
  2. Oracle의존성
  3. MongoDB와 동기화 캐시
  4. OleDB 종속성
  5. CLR 절차
  6. Read-Through를 통한 자동 재장전

다음 다이어그램은 NCache 데이터베이스 동기화 지원:

NCache 데이터베이스 동기화 아키텍처: 분산 캐시(Windows/Linux)는 실시간 이벤트 알림을 통해 SQL Server, Oracle, Cosmos DB 및 MongoDB와 동기화됩니다.
NCache RDBMS 및 NoSQL을 위한 실시간 데이터베이스 동기화 아키텍처.

SQL 종속성

SQL 종속성 사용 NCache 데이터베이스가 SQL Server인 경우. 캐시에서 항목을 추가하거나 업데이트할 때 캐시된 항목에 대해 SqlDependency를 지정할 수 있습니다. SQL Server는 추가, 업데이트 또는 제거가 있는지 데이터 세트를 모니터링하고 알립니다. NCache 데이터베이스 업데이트 직후 SQL 알림을 통해 전달됩니다. 이는 .NET 이벤트로 변환되는 데이터베이스 알림입니다.

SqlDependency는 다음 중 하나일 수 있습니다.

  • 인라인 쿼리
  • 저장 프로 시저

이 주제에 대한 자세한 내용은 다음에서 확인할 수 있습니다. SQL Server와 캐시 동기화 문서.

SQL 종속성 작동 방식

  • 트리거 : SQL Server는 데이터 변경(삽입, 업데이트 또는 삭제)을 감지합니다.
  • 알림: SQL Server는 .NET 이벤트 알림을 보냅니다. NCache.
  • 액션 : NCache 무결성을 유지하기 위해 항목을 자동으로 무효화하거나 다시 로드합니다.

인라인 쿼리 사용

동적으로 구성된 SQL 쿼리를 사용하여 SQL 종속성을 만드는 방법은 다음과 같습니다.

// Precondition: Cache is already connected
// Creating a connection string to get connected with the database
string connectionString = "your_connection_string_here";

// Getting products from the database
List<Product> products = FetchProductFromDB();

foreach (Product product in products)
{
    string productKey = $"Product: {product.ProductID}";

    // Creating an SQL dependency on the UnitPrice of product. Whenever the UnitPrice changes, the product is removed from the cache
    string query = $"SELECT UnitPrice FROM dbo.Products WHERE ProductID = {product.ProductID}";

    // Creating dependency
    SqlCacheDependency dependency = new SqlCacheDependency(connectionString, query);

    CacheItem productItem = new CacheItem(product);

    // Adding Dependency to product item
    productItem.Dependency = dependency;

    // Adding CacheItem in cache
    _cache.Add(productKey, productItem);
}

저장 프로시저 사용

저장 프로시저를 사용하여 .NET 코드에서 SQL 종속성을 사용하는 방법은 다음과 같습니다.

// Precondition: Cache is already connected

// Creating connection string to get connected with the database
string connectionString = "your_connection_string_here";
string spGetUnitPriceByProductID = "sp_GetUnitPriceByProductID";

// Getting products from the database
List<Product> products = FetchProductFromDB();

// Creating dictionary of CacheItems
Dictionary<string, CacheItem> cacheItems = new Dictionary<string, CacheItem>();

foreach (Product product in products)
{
    string productKey = $"Product: {product.ProductID}";

    // Creating Param to be passed in stored procedure dictionary
    SqlCmdParams paramProductID = new SqlCmdParams
    {
        Type = CmdParamsType.Int,
        Value = product.ProductID
    };

    // Creating stored procedure params
    Dictionary<string, SqlCmdParams> parameters = new Dictionary<string, SqlCmdParams>();
    parameters.Add("@ProductID", paramProductID);

    CacheItem productItem = new CacheItem(product);

    // Creating an SQL dependency on the UnitPrice of the product. Whenever the UnitPrice changes, the product is removed from the cache
    SqlCacheDependency dependency = new SqlCacheDependency(connectionString, spGetUnitPriceByProductID, SqlCommandType.StoredProcedure, parameters);

    // Adding Dependency to product item
    productItem.Dependency = dependency;

    cacheItems.Add(productKey, productItem);
}
// Adding CacheItems in cache
_cache.AddBulk(cacheItems);

오라클 종속성

NCache 오라클의 연속 쿼리 알림(CQN)을 활용하여 데이터베이스 변경 사항을 모니터링합니다. 기존 폴링 방식과 달리, 이 푸시 기반 메커니즘은 오라클 서버가 필요한 경우에만 통신하도록 보장합니다. NCache SQL 쿼리로 정의된 특정 데이터 세트가 수정될 때 작동합니다. 이를 통해 네트워크 오버헤드를 크게 줄이고 실시간 캐시 동기화를 보장합니다.

Oracle의존성 사용 NCache 데이터베이스가 Oracle 10g 이상이고 Windows 또는 Unix에서 실행 중인 경우. SqlDependency와 마찬가지로 캐시에 항목을 추가하거나 업데이트할 때 캐시된 항목에 대해 OracleDependency를 지정할 수 있습니다.

OracleDependency는 다음 중 하나일 수 있습니다.

  • 인라인 쿼리
  • 저장 프로 시저

그런 다음 Oracle Server는 추가, 업데이트 또는 제거 사항이 있는지 이 데이터 세트를 모니터링하고 해당 사항이 발생하면 알립니다. NCache 데이터베이스 업데이트 직후 Oracle Notifications를 통해 전달됩니다.

인라인 쿼리 사용

인라인 쿼리를 사용하여 .NET 코드에서 Oracle 종속성을 사용하는 방법은 다음과 같습니다.

// Precondition: Cache is already connected

// Creating a connection string to get connected with the database
string connectionString = "your_connection_string_here";

// Getting products from the database
List<Product> products = FetchProductFromDB();

foreach (Product product in products)
{
      string productKey = $"Product: {product.ProductID}";

      // Creating an Oracle dependency on the UnitPrice of the product. Whenever the UnitPrice changes, the product is removed from the cache
      string query = $"SELECT ROWID, UnitPrice FROM Products WHERE ProductID = {product.ProductID}";

      OracleCacheDependency dependency = new OracleCacheDependency(connectionString, query);

      CacheItem productItem = new CacheItem(product);

      // Adding Dependency to product item
      productItem.Dependency = dependency;

      // Adding CacheItem in cache
      cache.Add(productKey, productItem);
}

저장 프로시저 사용

다음과 같이 Oracle 종속성에서 매개변수화된 저장 프로시저 호출을 사용할 수 있습니다.

// Precondition: Cache is already connected

// Creating a connection string to get connected with the database
string connectionString = "your_connection_string_here";

string spGetUnitPriceByProductID = "sp_GetUnitPriceByProductID";

// Getting products from the database
List<Product> products = FetchProductFromDB();

foreach (Product product in products)
{
      string productKey = $"Product: {product.ProductID}";
      // Creating Param to be passed in stored procedure dictionary
      OracleCmdParams paramProductID = new OracleCmdParams
      {
            Type = OracleCmdParamsType.Int32,
            Value = product.ProductID
      };
      // Creating stored procedure params
      Dictionary<string, OracleCmdParams> parameters = new Dictionary<string, OracleCmdParams>();
      parameters.Add("@ProductID", paramProductID);

      CacheItem productItem = new CacheItem(product);

      // Creating an Oracle dependency on the UnitPrice of the product. Whenever the UnitPrice changes, the product is removed from the cache
      OracleCacheDependency dependency = new OracleCacheDependency(connectionString, spGetUnitPriceByProductID, OracleCommandType.StoredProcedure, parameters);

      // Adding Dependency to product item
      productItem.Dependency = dependency;

      // Adding CacheItem in cache
      cache.Add(productKey, productItem);
}

MongoDB와 동기화 캐시

NCache 사용자 지정 알림 종속성을 통해 캐시 무효화에 대한 유연성과 제어 기능을 제공합니다. MongoDB의 경우, 변경 스트림을 사용하여 캐시를 MongoDB 데이터베이스와 실시간으로 동기화할 수 있습니다.

이를 통해 MongoDB 컬렉션에서 삽입, 업데이트, 삭제 및 교체가 감지됩니다. NCache 변경 사항이 발생하면 해당 캐시 항목을 즉시 제거하거나 업데이트하여 캐시가 최신 상태로 유지되고 데이터베이스와 일관성을 유지할 수 있습니다.

다음은 .NET 애플리케이션에서 MongoDB의 변경 스트림을 사용하여 이러한 동기화를 구현하는 방법의 예입니다.

var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Customer>>()
    .Match("{ operationType: { $in: ['insert', 'update', 'replace', 'delete'] } }");
 
var cursor = collection.Watch(pipeline);
await cursor.ForEachAsync(change =>
{
    string cacheKey = $"Customer:CustomerID:{change.FullDocument.Id}";
    cache.Remove(cacheKey);
});

OleDB 종속성

OleDB 종속성 사용 NCache 데이터베이스가 SQL Server나 Oracle이 아니지만 OLEDB 호환 데이터베이스인 경우입니다. 데이터가 매우 빠르게 변경되는 경우 이벤트 알림이 너무 자주 발생할 수 있으므로, SQL Server와 Oracle에서 DbDependency를 사용할 수도 있습니다.

DbDependency에서는 데이터베이스에 ncache_db_sync라는 테이블을 생성합니다. 이 테이블에는 DbDependency를 통해 캐시된 각 항목에 대한 행이 하나씩 포함됩니다. 데이터베이스의 해당 데이터가 변경될 때 이 테이블의 행이 업데이트되도록 데이터베이스 트리거를 수정합니다. NCache 업데이트된 행에 대해 이 테이블을 폴링하므로 한 폴링에서 NCache 수천 개의 행을 가져와 데이터베이스와 동기화합니다.

다음은 .NET 코드에서 DbDependency를 사용하는 방법입니다.

DBCacheDependency oledbDependency = DBDependencyFactory.CreateOleDbCacheDependency(connectionString, "PrimaryKey:dbo.Products");

var cacheItem = new CacheItem(product);
cacheItem.Dependency = oledbDependency;
cache.Insert(key, cacheItem);

CLR 절차

캐시에 매우 많은 항목이 있고 모든 항목을 데이터베이스와 동기화해야 하는 경우 다음을 작성하는 것이 훨씬 좋습니다. CLR 절차 Windows의 SQL Server에서 이 CLR 프로시저는 관련 데이터가 변경될 때 데이터베이스 트리거에서 호출됩니다. 그런 다음 이 CLR 프로시저를 비동기식으로 만듭니다. NCache 캐시에서 해당 캐시 항목을 추가, 업데이트 또는 제거하기 위한 API 호출입니다.

다음은 업데이트된 개체를 제거하는 CLR 프로시저의 예입니다.

[Microsoft.SqlServer.Server.SqlProcedure]
    public static void RemoveOnUpdate(string cacheName, string key)
    {

        // Connect to the cache
        ICache cache = CacheManager.GetCache(cacheName);

        // Remove specified item
        cache.Remove(key);

        // Dispose the cache
        cache.Dispose();
    }

Read-Through 핸들러를 사용한 자동 재로드

데이터베이스 동기화의 기본 동작은 데이터베이스의 해당 데이터가 변경되면 캐시된 항목을 데이터베이스에서 제거하는 것입니다. 하지만 단순히 최신 버전의 데이터로 업데이트하려는 경우도 있습니다.

이 필요를 처리하기 위해, NCache 데이터베이스 동기화를 다음과 결합할 수 있습니다. 전체 읽기 캐싱 기능 NCache. 이것으로, NCache Read-through 핸들러를 호출하여 캐시된 항목의 최신 복사본을 다시 로드한 다음 캐시를 업데이트합니다. 이 기능은 동기화할 수 있는 유연성을 제공합니다. NCache 다음과 같은 (그리고 그 외 더 많은) 관계형 또는 NoSQL 데이터베이스가 구성된 경우:

  1. SQL 서버
  2. 신탁
  3. MongoDB의

다음 코드 조각은 데이터를 대량으로 자동으로 다시 로드하는 방법을 보여줍니다. NCache Read-through를 사용하여 데이터베이스에서 가져옵니다. 자세한 내용은 여기에서 확인하세요.

String[] keys = { "Product:1001", "Product:1002",
"Product:1003","Product:1004"};

// Specify the readThruOptions for Read-through operations
var readThruOptions = new ReadThruOptions();
readThruOptions.Mode = ReadMode.ReadThru;

// Retrieve the dictionary of Products with corresponding products
IDictionary<string, Product> retrievedItems = cache.GetBulk<Product>(keys, readThruOptions);

동기화 지원 환경

  • 관계형: SQL Server, Oracle, PostgreSQL, MySQL(OLEDB/CLR을 통해).
  • NoSQL : MongoDB, Azure Cosmos DB.
  • 정의 : CustomDependency 및 Read-Through 핸들러를 통해 모든 데이터 소스를 사용할 수 있습니다.

적절한 동기화 메커니즘 선택하기

시나리오 권장 메커니즘 NCache 사용된 기능
표준 SQL/Oracle 업데이트 데이터베이스 알림 SQL 종속성 / Oracle의존성
대규모/일괄 업데이트 CLR 절차 CLR 저장 프로시저(비동기)
일반/레거시 데이터베이스 투표 Db종속성 (OLEDB를 통해)
NoSQL 아키텍처 스트림 변경 사용자 지정 종속성을 통한 MongoDB 동기화

다음에 무엇을할지?

자주 묻는 질문 (FAQ)

NCache "알림 기반" 동기화 모델을 사용합니다. 다음과 같은 기능을 활용하여 SQL 종속성 Oracle의존성데이터베이스는 레코드가 업데이트되거나 삭제되는 순간 캐시에 실시간 신호를 보냅니다. 이를 통해 NCache 오래된 항목을 즉시 무효화하거나 다시 로드합니다.

예. 기본적으로 알림 기능을 지원하지 않는 데이터베이스의 경우, NCache 폴링 기반 종속성(DbDependency)을 제공합니다. NCache 데이터베이스의 동기화 테이블을 주기적으로 확인하여 변경 사항을 감지하고, 모든 OLEDB 호환 소스와 호환성을 유지합니다.

대규모 업데이트가 발생하는 환경에서는 CLR 저장 프로시저를 사용하는 것이 좋습니다. 이러한 프로시저는 SQL Server에서 직접 실행되며 비동기적으로 호출을 수행합니다. NCache수천 건의 개별 .NET 이벤트 알림으로 인한 오버헤드를 방지합니다.

전혀. NCache MongoDB의 Change Streams를 사용하여 컬렉션 업데이트를 실시간으로 감지하고 동기화합니다. 다른 NoSQL 소스의 경우에도 활용할 수 있습니다. NCache만료 또는 무효화 시 데이터를 자동으로 다시 로드하는 읽기 통과(Read-Through) 제공업체입니다.

NCache 고가용성을 위해 설계되었습니다. 데이터베이스 연결이 중단될 경우, NCache 동기화를 재시도하도록 구성하거나, 오래된 데이터가 무기한으로 남아 있지 않도록 TTL(Time-to-Live) 설정을 대체 수단으로 사용할 수 있습니다.

문의하기

전화

+1 214-619-2601 (미국)

© 저작권 Alachisoft 2002 - . 판권 소유. NCache 는 Diyatech Corp.의 등록상표입니다.