SQL Server 캐시 종속성
에는 다양한 메커니즘이 있습니다. NCache 캐시 전반에 걸쳐 데이터 동기화를 유지합니다. 사용자가 데이터를 데이터베이스와 동기화된 상태로 유지하려는 시나리오가 있을 수 있으므로 모든 데이터베이스 업데이트가 캐시에 알립니다. 이렇게 하면 캐시의 데이터가 최신 상태로 유지되고 업데이트된 데이터 세트에서 작업이 발생합니다.
NCache Microsoft SQL Server 2005 이상과 캐시를 동기화하는 SQL 종속성 기능을 제공합니다. 항목이 다음과 같이 추가됩니다. SqlCacheDependency (에 의해 제공 NCache), 데이터베이스의 쿼리 결과 집합을 나타내는 SQL 문을 지정합니다. NCache 그런 다음 결과 세트에 대해 데이터베이스와의 링크를 설정합니다. 애플리케이션이 업데이트되면 SQL Server는 이벤트 알림을 발생시킵니다. NCache 분산 캐시에서 해당 항목을 잡아서 제거합니다.
SQL 종속성을 사용하기 전에 SQL Server 환경을 설정하십시오. SQL 종속성을 생성하려면 다음을 수행합니다.
- 브로커 서비스 활성화
- 데이터베이스 권한 활성화
자세한 내용은 다음을 참조하십시오. SQL 서버 환경 설정 관리자 안내서의 섹션을 참조하세요.
SQL Server 캐시 종속성을 사용하기 위한 전제 조건
API를 통해 SQL Server 종속성이 있는 데이터 추가
SQL 종속성을 사용하여 캐시에 데이터를 추가하려면 NCache 제공 SqlCacheDependency
수업. 이렇게 하면 SQL 종속성을 사용하여 캐시에 항목이 추가됩니다.
다음 예에서는 항목에 SQL 종속성을 추가한 다음 다음을 사용하여 항목을 캐시에 추가합니다. Insert
방법. 그만큼 Insert
메서드는 종속성이 있는 새 항목을 추가하고, 이 데이터가 이미 캐시에 있으면 덮어씁니다.
// Creating connection string to get connected with database.
string connectionString = "your_connection_string_here";
// Getting products from 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);
}
// Creating connection spring to get connected with database
String connectionString = "your_connection_string_here";
// Getting products from the database
List<Product> products = FetchProductFromDB();
for (Product product : products) {
String productKey = "Product:" + product.getProductID();
// Creating an SQL dependency on the UnitPrice of the product. Whenever the UnitPrice changes, the product is removed from the cache.
String query = "SELECT UnitPrice FROM dbo.Products WHERE ProductID = " + product.getProductID();
// Creating a dependency
SqlCacheDependency dependency = new SqlCacheDependency(connectionString, query);
CacheItem productItem = new CacheItem(product);
// Adding Dependency to the product item
productItem.setDependency(dependency);
// Adding CacheItem to the cache
cache.add(productKey, productItem);
System.out.println("Product added to cache: " + productKey);
}
// This is an async method
// Creating a connection string to establish connection with the database
var connection = new ActiveXObject("adodb.connection");
let connString = "your_connection_string_here";
let query = "SELECT CustomerID, Address, City FROM dbo.Customers WHERE CustomerID = ?";
let queryCommand = new QueryCommand(query);
queryCommand.getParameters().put("CustomerID", this.customerId);
connection.Open(query, connString);
// Creating SQL dependency
let sqlDependency = new ncache.SqlCacheDependency(connString, query);
// Get orders against customerId
let orders = await this.fetchOrdersByCustomerId(this.customerId);
for (let order in orders)
{
// Generate a unique key for this order
let key = "Order:" + order.OrderId;
// Create a new cache item and add sql dependency to it
let cacheItem = new ncache.CacheItem(order);
cacheItem.setDependency(sqlDependency);
// Add cache item in the cache with sql dependency
await this.cache.insert(key, cacheItem);
// For successful addition of item with SQL Dependency
// Update the record in the database and check if key is present
}
connection.close();
# Creating a connection string to establish connection with the database
conn_string = "your_connection_string_here"
query = "SELECT CustomerID, Address, City FROM dbo.Customers WHERE CustomerID = ?"
query_command = ncache.QueryCommand(query)
query_command.set_parameters({"CustomerID": "ALFKI"})
# Creating SQL dependency
sql_dependency = ncache.SqlCacheDependency(conn_string, query)
# Get orders against Customer ID
orders = fetch_orders_by_customer_id("ALFKI")
for order in orders:
# Generate a unique key for this order
key = "Order:" + order.get_order_id()
# Create a new cache item and add sql dependency to it
cache_item = ncache.CacheItem(order)
cache_item.set_dependency(sql_dependency)
# Add cache item in the cache with sql dependency
cache.insert(key, cache_item)
# For successful addition of item with SQL Dependency
# Update the record in the database and check if key is present
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
저장 프로시저를 사용하여 SQL 종속성이 있는 데이터 추가
NCache 저장 프로시저를 사용하여 항목에 대한 SQL 종속성을 제공할 수 있습니다. 다음을 사용하여 이 프로시저와 함께 전달될 매개변수를 지정할 수도 있습니다. SqlCacheDependency
방법.
다음 예에서는 다음을 사용하여 저장 프로시저를 통해 SQL 종속성이 있는 캐시에 항목을 추가합니다. 끼워 넣다 방법. 그만큼 Insert
메서드는 종속성이 있는 새 항목을 추가하고, 이 데이터가 캐시에 이미 존재하는 경우 해당 속성을 덮어씁니다.
// Creating connection string to get connected with database.
string connectionString = "your_connection_string_here";
string spGetUnitPriceByProductID = "sp_GetUnitPriceByProductID";
// Getting products from 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 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);
String connectionString = "your_connection_string_here";
String spGetUnitPriceByProductID = "sp_GetUnitPriceByProductID";
// Getting products from the database
List<Product> products = FetchProductFromDB();
// Create a map to store CacheItems.
Map<String, CacheItem> cacheItems = new HashMap<>();
for (Product product : products) {
String productKey = "Product:" + product.getProductID();
// Creating Param to be passed in the stored procedure dictionary.
SqlCmdParams paramProductID = new SqlCmdParams();
paramProductID.setCmdParamsType(CmdParamsType.Int);
paramProductID.setValue(product.getProductID());
// Creating stored procedure params.
Map<String, SqlCmdParams> parameters = new HashMap<>();
parameters.put("@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 the product item.
productItem.setDependency(dependency);
cacheItems.put(productKey, productItem);
System.out.println("Added product to cache items: " + productKey);
}
// Adding CacheItems in cache using addBulk method.
cache.addBulk(cacheItems);
System.out.println("Products added to cache.");
// This is an async method
// Creating a connection string to establish connection with the database
var connection = new ActiveXObject("adodb.connection");
let connString = "your_connection_string_here";
connection.Open(connString);
// Name of the stored procedure item is dependent un
let storedProcName = "GetCustomerByID";
// Specify the customerID passed as parameters
let sqlCmdParams = new Map();
sqlCmdParams.set("CustomerID", this.customerId);
// Create sql dependency
// In case the stored procedure has no parameters, pass null as the SqlCmdParams value
let sqlCacheDependency = new ncache.SqlCacheDependency(connString, storedProcName,
ncache.SqlCommandType.StoredProcedure, sqlCmdParams);
// Get orders from database against customerId
let orders = await this.fetchOrdersByCustomerId(this.customerId);
for (let order in orders)
{
// Generate a unique cache key for this order
let key = "Order:" + order.OrderId;
// Create a new cache item and add sql dependency to it
let item = new ncache.CacheItem(order);
item.setDependency(sqlCacheDependency);
// Add cache item in the cache with sql dependency
this.cache.insert(key, item);
// For successful addition of item with SQL Dependency
// Update the record in the database and check if key is present
}
connection.close();
# Creating a connection string to establish connection with the database
conn_string = "your_connection_string_here"
# Name of the stored procedure item is dependent upon
stored_proc_name = "GetCustomerByID"
# Specify the customerID passed as parameters
sql_cmd_params = {"CustomerID": "ALFKI"}
# Create sql dependency
# In case the stored procedure has no parameters, pass null as the SqlCmdParams value
sql_cache_dependency = ncache.SqlCacheDependency(conn_string, stored_proc_name, ncache.SqlCommandType.STORED_PROCEDURE, sql_cmd_params)
# Get orders from database against customerId
orders = fetch_orders_by_customer_id("ALFKI")
for order in orders:
# Generate a unique cache key for this order
key = "Order:" + order.get_order_id()
# Create a new cache item and add sql dependency to it
item = ncache.CacheItem(order)
item.set_dependency(sql_cache_dependency)
# Add cache item in the cache with sql dependency
cache.insert(key, item)
# For successful addition of item with SQL Dependency
# Update the record in the database and check if key is present
중대한
- 사용자가 데이터베이스에 대해 더 제한된 액세스 권한을 갖는 환경에서 사용자는 SQL 서비스 및 대기열을 생성해야 합니다. NCache "를 확인하여 프로세스를 진행합니다.사용자 지정 SQL 알림 모드 사용” 확인란을 선택합니다. 옵션 의 탭 NCache 관리센터.
- 스크립트를 사용하여 필요한 SQL 서비스 및 대기열을 생성할 수도 있습니다. NCache서비스큐.sql 에 위치 %NCHOME%\bin\resources.
추가 자료
NCache SQL 종속성에 대한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.런타임.종속성 네임 스페이스.
자바 : COM.alachisoft.ncache.runtime.종속성 네임 스페이스.
Node.js : SqlCacheDependency 클래스입니다.
파이썬 : ncache.runtime.종속성 클래스입니다.