Connect to Cache
After successfully configuring NCache, you can start developing applications utilizing NCache by embedding NCache API calls. In order to do that, you need to connect to the cache. Single as well as multiple caches can be connected in a single application. Moreover cache can be connected with security credentials.
Pre-Requisites for Connecting to Cache
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
Alachisoft.NCache.Web.Security
(for connecting with security credentials)
- Cache must be running.
- Make sure that the data being added is serializable.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Connect to Single Cache
NCache provides InitializeCache method to get an instance of a NCache’s cache, with support of method overloading to accommodate multiple scenarios' handling. This method uses all the properties specified in the client configuration file (client.ncconf) to initialize the cache.
The following example connects to a cache named myPartitionedCache using the InitializeCache
method.
try
{
// Initialize the cache
Cache cache = null;
// Specify the name of the cache
string cacheName = "mypartitionedcache";
// Connect to the cache
cache = NCache.InitializeCache(cacheName);
}
catch (OperationFailedException ex)
{
if (ex.Message.Contains("No server is available to process the request"))
{
// Make sure NCache Service is running
// Make sure that the cache is running
}
else if (ex.Message.Contains("'client.ncconf' not found or does not contain server information"))
{
// client.ncconf must have server information
}
else if (ex.Message.Contains("cacheId cannot be an empty string"))
{
// Make sure that the cache name is not an empty string
}
else
{
// Exception can occur due to:
// Connection failures
// Operation performed during state transfer
// Operation timeout
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Connect to Multiple Caches
Using InitializeCache you can have multiple caches initialized within a single application. This will help you manage the data of multiple caches using one application.
For this exercise, both caches need to be configured previously and they must be in running state.
Following example connects to two caches using the InitializeCache
method.
try
{
// Initialize the caches
Cache cache1 = null;
Cache cache2 = null;
// Specify the cache names
string cacheName1 = "mypartitionedcache";
string cacheName2 = "myreplicatedcache";
// Connect to the caches
cache1 = NCache.InitializeCache(cacheName1);
cache2 = NCache.InitializeCache(cacheName2);
}
catch (OperationFailedException ex)
{
if (ex.Message.Contains("No server is available to process the request"))
{
// Make sure NCache Service is running
// Make sure that the caches are running
}
else if (ex.Message.Contains("'client.ncconf' not found or does not contain server information"))
{
// client.ncconf must have server information
}
else if (ex.Message.Contains("cacheId cannot be an empty string"))
{
// Make sure that the cache names are not an empty string
}
else
{
// Exception can occur due to:
// Connection failures
// Operation performed during state transfer
// Operation timeout
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Connect to Cache Using CacheInitParams
CacheInitParams
allows editing values of cache properties at initialization
time. These values are the same which can be configured through client.ncconf file.
Warning
Any configuration specified through CacheInitParams
will override the value in client.ncconf for that particular client.
Refer to the CacheInitParams API Documentation for more detail on properties of this class.
In this example, the values of RetryInterval
, ConnectionRetries
, EnableKeepAlive
and KeepAliveInterval
properties can be changed. For this application these values will be used
instead of the ones specified in client configuration file.
try
{
// Initialize the cache
Cache cache = null;
// Create new InitParam instance
CacheInitParams initParam = new CacheInitParams();
// Specify the parameters to be set
initParam.RetryInterval = 3;
initParam.ConnectionRetries = 2;
initParam.EnableKeepAlive = true;
initParam.KeepAliveInterval = 30;
// Specify the cache name
string cacheName = "mypartitionedcache";
// Connect to the cache
cache = NCache.InitializeCache(cacheName, initParam);
}
catch (OperationFailedException ex)
{
if (ex.Message.Contains("No server is available to process the request"))
{
// Make sure NCache Service is running
// Make sure that the cache is running
}
else if (ex.Message.Contains("'client.ncconf' not found or does not contain server information"))
{
// client.ncconf must have server information
}
else if (ex.Message.Contains("cacheId cannot be an empty string"))
{
// Make sure that the cacheName is not an empty string
}
else
{
// Exception can occur due to:
// Connection failures
// Operation performed during state transfer
// Operation timeout
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Connect to Cache with Security Credentials
If security has been enabled, you need to provide the security credentials while initializing caches so that the authorized user can perform the operation. For more details on Security and using security in NCache, see NCache Security.
try
{
// Specify the cache name
// Specify the user credentials
string cacheName = "mypartitionedcache";
string userName = "username";
string password = "mypassword";
// Initialize the cache init params
CacheInitParams initParam = new CacheInitParams();
// Enter the credentials
initParam.PrimaryUserCredentials = new SecurityParams(userName, password);
// Connect to the cache using the security credentials
Cache cache = NCache.InitializeCache(cacheName, initParam);
}
catch (SecurityException ex)
{
// If the user doesnt have the permissions to access the cache
}
catch (OperationFailedException ex)
{
if (ex.Message.Contains("No server is available to process the request"))
{
// Make sure NCache Service is running
// Make sure that the cache is running
}
else if (ex.Message.Contains("'client.ncconf' not found or does not contain server information"))
{
// client.ncconf must have server information
}
else if (ex.Message.Contains("cacheId cannot be an empty string"))
{
// Make sure that the cacheName is not an empty string
}
else
{
// Exception can occur due to:
// Connection failures
// Operation performed during state transfer
// Operation timeout
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Troubleshooting
"No server available to process request"
Sometimes a cluster can not be created because the Server and Cluster ports are blocked by firewall. Following error message can occur in this case:
Error: "No server available to process request"
Workaround
Make sure that the Server port (at which NCache Service starts and accepts different client connections) is not blocked by firewall. Default value of this port is '9800'. You can change the default value from Alachisoft.NCache.Service.exe.config file.
- NCache Manager unable to connect with NCache Service:
If NCache Manager is unable to connect with NCache Service, even when it is started, then your system firewall might be blocking Service port. Unblock Service port from system firewall.
"Unable to communicate with server node"
Cluster nodes can also be unable to communicate with each other because of the aforementioned reason as well.
Error: "Unable to communicate with server node"
Workaround
See if your firewall is allowing the Cluster port. Cluster port is a port at which nodes in a cluster communicate. You can change the default value of these ports from NCache Manager. If you have specified a port range in NCache Manager, unblock all ports in range.
Client Socket Deadlock
You may experience a deadlock situation on your client socket because of a long wait for a response from the cache server. This may also result in a lot of waiting threads that may cause performance issues.
Workaround
Step1: Changes on Server Side
Go to Alachisoft.NCache.Service.exe.config located at
%NCHOME%/bin/service
:
Add the following lines in the configuration file:
<add key = "NCacheServer.EnableBadClientDetection" value = "true" />
The value "true" indicates that BadClientDetection is enabled on your client socket. This means that now if a deadlock situation arises on your client socket, the socket will be reset. The default value of this property is "false".
<add key = "NCacheServer.ClientSocketSendTimeout" value = "10" />
When you have enabled BadClientDetection
, you can specify the time interval after which the socket is reset in case of a deadlock. The default value of this property is "10" and this value can not be less than 1.
A few other properties have also been introduced in Alachisoft.NCache.Service.exe.config to help with this issue. Please configure these properties as follows:
<add key ="NCacheServer.EventPriorityRatio" value="30"/>
On the server-side a priority queue is used for events and cache operations. You can configure a ratio of events and cache operations for this queue through the property called EventPriorityRatio
. The default value of this property is 30 which indicates a ratio 30:70 for events and cache operations. The value of this property can not be less than 1.
<add key ="NCacheServer.EventBulkCount" value="50"/>
The cache server now sends events to clients in bulk. Through this property you can set the number of items to be sent in bulk. By default this value is 50 and the value can not be less than 1. This is available in client version 4124 and above.
<add key ="NCacheServer.EventBulkCollectionInterval" value="2"/>
This property is used to set the time interval, in seconds, after which bulk of events is fired even in case the bulk count does not reach the EventBulkCount
that the user has specified. Default value for this property is 2 seconds and the value can not be less than 1.
Restart the NCache service for these changes to take effect.
Step2: Changes on Client Side
Please make the following changes in your App.config/Web.config file:
<configuration>
<appSettings>
c <add key ="NCacheClient.AsynchronousEventNotification" value="true"/>
<add key ="NCacheClient.NumberofEventProccesingThreads" value="2"/>
</appSettings>
</configuration>
AsynchronousEventNotification
: Specifies whether events will be fired asynchronously or synchronously on client side. The default value is "true" which indicates that events will be fired asynchronously. The value "false" means that events will be fired synchronously on client side.
NumberofEventProcessingThreads
: When the user has configured events to be fired synchronously, this flag is used to specify the number of threads which will process these events on client side. A very large value can cause performance issues.
See Also
Data in Cache
Basic Cache Operations
Handling Failures in Cache
NCache Management API