SQL Server キャッシュの依存関係
にはさまざまなメカニズムがあります NCache キャッシュ全体でデータの同期を維持します。 ユーザーがデータベースとのデータの同期を維持したい場合、データベースの更新ごとにキャッシュに通知するシナリオが考えられます。 こうすることで、キャッシュ内のデータが最新の状態に保たれ、更新されたデータ セットに対して操作が行われます。
NCache は、キャッシュを Microsoft SQL Server 2005 以降と同期する SQL 依存関係の機能を提供します。 項目が追加されます SqlCacheDependency (によって提供された NCache)、データベース内のクエリ結果セットを表す SQL ステートメントを指定します。 NCache 次に、結果セットに対してデータベースとのリンクを確立します。 アプリケーションが更新されると、SQL Server はイベント通知を発行します。 NCache 対応する項目をキャッチし、分散キャッシュから削除します。
SQL 依存関係を使用する前に、SQL Server 環境をセットアップします。 SQL 依存関係を作成するには:
- ブローカーサービスを有効にする
- データベース権限を有効にする
詳細については、 SQLServer環境のセットアップ 管理者ガイドのセクションを参照してください。
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
Note
操作がフェイルセーフであることを保証するために、で説明されているように、アプリケーション内の潜在的な例外を処理することをお勧めします。 失敗の処理.
ストアドプロシージャを使用して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 サービスとキューを作成することもできます NCacheServiceQueue.sql にあり %NCHOME%\bin\resources.
その他のリソース
NCache SQL 依存関係のサンプル アプリケーションを提供します。 GitHubの.
も参照してください
。ネット: Alachisoft.NCache.Runtime.Dependency 名前空間
Java: comの。alachisoft.ncache.runtime.dependency 名前空間
Node.js: SqlCacheDependency とに提供されます。
Python: ncache.runtime.dependency とに提供されます。