How to Programmatically Connect to a Cache

NCache provides two options through which you can connect to a cache. One is through the NCache configuration files and the other is through NCache connection APIs. Configuration files are sometimes difficult to manage, hence, instead of the applications picking up certain settings from them, you can dynamically provide these settings through your application code.

You can override the default cache connection settings present in the client.ncconf file through the CacheConnectionOptions class.

Here is a step-by-step process to use CacheConnectionOptions to add server information of a cache cluster.

Step 1: Install NuGet Package and Include Namespaces

Install the NuGet package Alachisoft.NCache.SDK which contains the client libraries. Then include the following namespaces in your application:

  • Alachisoft.NCache.Client
  • Alachisoft.NCache.Runtime.Exceptions

Step 2: Initialize CacheConnectionOptions Object

Initialize the CacheConnectionOptions object as follows:

CacheConnectionOptions cacheConnectionOptions = new CacheConnectionOptions();

Step 3: Add Server Information

Add Cache Server connection settings by using the CacheConnectionOptions object created in the previous step as follows:

cacheConnectionOptions.LoadBalance = true;
cacheConnectionOptions.ConnectionRetries = 5;
cacheConnectionOptions.Mode = IsolationLevel.OutProc;
cacheConnectionOptions.ClientRequestTimeOut = TimeSpan.FromSeconds(90);
cacheConnectionOptions.RetryInterval = TimeSpan.FromSeconds(5);
cacheConnectionOptions.ServerList = new List<ServerInfo>();
{
    new ServerInfo("20.200.20.48",9800),
    new ServerInfo("20.200.20.47",9800)
};

CacheConnectionOptions allows specifying values of cache properties, some of which are explained below while establishing a connection to the cache. These values are the same and can be configured through the client.ncconf file as well.

  • Ports: Client connection port 9800
  • EnableClientLogs: Information about client logs
  • ConnectionRetries: Number of retries to re-establish a broken connection between client and server.
  • RetryInterval: Time in seconds to wait between two connection retries.
  • Read More

Step 4: Use Connection API

Add the CacheConnetionOptions to the GetCache API call. Also, keep in mind that the ICache handle should be initialized once at application startup and then use it throughout the application, there is no need to reinitialize it.

string clusteredCache = "demoClusteredCache";
ICache cache = CacheManager.GetCache(clusteredCache, cacheConnectionOptions);

You will be successfully connected to the cache cluster. You can follow the complete guide on how to connect to NCache.

What to Do Next?

Signup for monthly email newsletter to get latest updates.

© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.