데이터베이스는 . NET 대규모 데이터 집합을 효율적으로 가져오고 조작할 수 있습니다. 그러나 높은 트랜잭션 데이터를 처리할 때 데이터베이스는 .NET 애플리케이션의 성능 저하를 초래합니다. 이는 데이터베이스를 여러 머신으로 확장할 수 없기 때문입니다. 데이터베이스 계층 전용 서버 머신은 하나만 가질 수 있고 더 추가할 수 없습니다. 따라서 데이터베이스는 성능 병목 현상이 됩니다. 이 문제를 해결하기 위해 다음과 같은 분산 캐싱 솔루션을 사용합니다. NCache 데이터베이스에 대한 불필요하고 비용이 많이 드는 이동을 완화합니다.
데이터베이스를 캐시하는 방법?
데이터베이스 캐싱은 생각보다 훨씬 간단합니다. 캐싱 계층을 다음과 같은 캐시와 통합해야 합니다. NCache 데이터베이스 데이터가 캐시에서 제공되도록 애플리케이션과 데이터베이스 계층 간에 편의를 위해 가장 일반적인 캐시 사용 패턴 XNUMX가지를 요약했습니다. 아래에 요약되어 있습니다.
1. 개체 캐싱
이 전략은 데이터가 캐시에 없으면 데이터베이스에서 데이터를 가져온 다음 다음과 같이 캐시에 삽입하는 것을 제안합니다. NCache. 후속 호출은 나중에 캐시에서 처리됩니다. 부실 데이터와 관련된 문제의 경우 다음을 추가합니다. 만료 ~로 캐시 아이템 데이터베이스에서 새로 고칠 수 있습니다.
다음 코드는 Customer 인스턴스가 있는 경우 캐시에서 가져옵니다. 그렇지 않으면 데이터베이스에서 가져오고 연속 호출에서 캐시 적중을 위해 캐시에 추가합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
var key = "Customer:1001"; // Get Customer from cache if it exists var customer = cache.Get<Customer>(key); // If customer does not exist in cache if (customer == null) { // Fetch from database customer = GetCustomerFromDB(1001); // Create sliding expiration of 15 seconds. Cache removes item after this time var expiration = new Expiration (ExpirationType.Sliding, TimeSpan.FromSeconds(15.0)); var cacheItem = new CacheItem(customer) { Expiration = expiration }; // Insert the item with expiration into cache cache.Insert(cacheKey, cacheItem); } |
NCache 세부 정보 데이터 캐싱 문서 NCache 프로그래머 가이드
2. 참조 데이터 캐시 및 SQL 쿼리를 사용하여 검색
읽기만 하고 자주 변경되지 않는 데이터를 참조 데이터라고 합니다. .NET 애플리케이션이 반복적으로 데이터를 읽고 가끔 데이터베이스에 데이터를 쓰는 것은 매우 일반적입니다. 캐시(예: NCache)은 이러한 데이터와 가장 빠르게 작동하므로 참조 데이터로 사용될 때 더 강력합니다.
전체 참조 데이터를 캐시한 다음 사용하는 것이 좋습니다. 캐시를 검색하는 SQL 쿼리 데이터베이스로 이동하는 대신 이를 위해. 전체 참조 데이터 세트(예: 모든 고객)를 캐시하지 않으면 일부 데이터가 데이터베이스에만 있기 때문에 캐시에 대한 SQL 쿼리는 유효하지 않은 결과를 반환합니다.
당신이 이미 캐시를 미리 로드 모든 참조 데이터와 함께 다음 예에서는 검색 방법을 설명합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Pre-Requisite: All customer instances have already been added into cache var customerName = "John Smith"; // Write SQL query for cache var query = "SELECT $Value$ FROM Northwind.Model.Customer WHERE Name = ?"; // Create the query command that cache understands from the query var queryCommand = new QueryCommand(query); // Provide the parameters for the query queryCommand.Parameters.Add("Name", customerName); // Execute the query on cache var reader = cache.SearchService.ExecuteReader(queryCommand, true); var customer; // If a valid projection was made in the query if (reader.FieldCount > 0) { while (reader.Read()) { customer = reader.GetValue<Customer>(1); // Perform operation according to business logic } } |
NCache 세부 정보 SQL 캐싱 문서 데이터 캐싱 문서
3. 캐시에서 일대다 관계 처리
대부분의 데이터에는 데이터 간의 관계가 포함되어 있습니다. 예를 들어 Northwind 데이터베이스(Microsoft에서 사용)의 컨텍스트에서 'Orders' 테이블은 'Customers' 테이블과 관련됩니다. 이러한 엔터티는 .NET 애플리케이션 도메인에서 관련 엔터티로 간주됩니다. 다음과 같은 캐시 사용 NCache, 캐시 내에서도 이러한 엔티티를 연관시킬 수 있습니다.
이것은에 의해 수행 모든 관련 엔터티를 태그 식별자와 연결 고객의 각 주문을 개별적으로 가져오는 대신 태그 식별자를 통해 캐시를 검색하여 한 번의 호출로 고객의 모든 주문을 가져올 수 있습니다. 주어진 예제 코드는 우리가 어떻게 이 동작을 가져올 수 있는지 보여줍니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
var cacheKey = "Customer:1001"; var tagName = "Customer:1001_Orders"; // Check if customer exists in cache var cachedCustomer = cache.Get<Customer>(cacheKey); // If customer does not exist in cache if (cachedCustomer == null) { // Fetch from database var customer = GetCustomerFromDb(1001); // Insert customer into cache cache.Insert(cacheKey, customer); // Fetch orders of the customer from database var relatedOrders = GetRelatedOrdersFromDb(customer); // Create a tag for all orders of the customer var tag = new Tag(tagName); foreach (Order order in relatedOrders) { var orderCacheKey = $"Customer:1001_Order:{order.OrderID}"; // Create a cache item and set the tag identifier var orderCacheItem = new CacheItem(order) { Tags = new[] { tag } }; // Insert the tagged cache item into cache cache.Insert(orderCacheKey, orderCacheItem); } } else { // Item exists in the cache // Create a tag to fetch the related orders var tagIdentifier = new Tag(relatedEntityIdentifier); // Fetch the related orders based on the tag identifier var cachedOrders = cache.SearchService.GetByTag<Order>(tagIdentifier); } |
NCache 세부 정보 태그가 지정된 데이터 문서 캐시 데이터 캐싱 문서
4. 데이터베이스 쿼리 결과 캐싱(트랜잭션 데이터)
대부분의 경우 데이터베이스의 데이터는 쿼리 결과 집합의 형태로 반환됩니다. 이 전략은 전체 결과 집합을 캐시에 삽입하여 연속적인 쿼리가 캐시에서 제공되도록 제안합니다. 동일한 기준을 사용하는 쿼리는 항상 동일한 결과 집합을 참조합니다. 따라서 쿼리 명령 자체를 결과 집합의 고유 식별자로 간주하고 캐시의 키로 사용할 수 있습니다.
다음 코드는 쿼리 결과 집합을 컬렉션으로 캐시하는 방법을 보여줍니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Query to select East Coast Customers var query = "SELECT * FROM Northwind.Model.Customer WHERE Region = ‘EastCoast’"; // Create cache key based on the query var key = query; // Fetch the entities based on query var resultSet = cache.Get<IList<Customer>>(key); // If data against query not found in cache if (resultSet == null) { // Fetch the result set from database var customers = GetCustomersFromDb(query); // Convert the result set into a collection var cacheReadyCustomers = customers.ToList(); // Add result set to cache against query cache.Insert(cacheKey, cacheReadyCustomers); } |
NCache 세부 정보 데이터 캐싱 문서 SQL 캐싱 문서
결론
보시다시피, 다음과 같은 캐시를 사용하여 .NET 애플리케이션에서 데이터베이스를 캐싱합니다. NCache 아주 쉽습니다. 애플리케이션의 사용 패턴에 따라 데이터를 캐시하고 데이터베이스에 대해 수행하는 것처럼 쿼리를 통해 가져올 수 있습니다.
더욱이, NCache 메모리 내 분산 캐싱 솔루션입니다. 데이터베이스를 사용할 때 발생하는 모든 문제는 데이터베이스에서 처리되며 표준 요구 사항 등을 포함한 캐시에 대한 모든 구현이 있습니다.