• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

How to Connect to Cache

NCache applications connect to a running cache through the CacheManager.GetCache API. The application specifies the cache name and, when required, connection information such as server endpoints and security credentials. If server endpoints are not supplied in code, NCache reads them from the ncache section of the application configuration (appsettings.json, app.config, or web.config).

The following examples demonstrate connecting to single and multiple caches, specifying connection options, connecting through a load balancer, and authenticating to secured caches. Client configuration settings are managed centrally by the cache server rather than configured through client-side connection options.

Important

Starting with NCache 5.3.8, CacheConnectionOptions is no longer supported. Use the new ConnectionOptions class to configure cache connections.

Prerequisites

Before using the NCache Client-side APIs, ensure that the following prerequisites are fulfilled:

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
  • Install the following NuGet packages in your .NET client application:
    • NCache: Alachisoft.NCache.SDK
    • NCache Open Source: Alachisoft.NCache.Opensource.SDK
  • Include the following namespaces in your application:
    • Alachisoft.NCache.Client
    • Alachisoft.NCache.Runtime.Exceptions
  • The cache must be running.
  • Make sure that the data being added is serializable.
  • For API details, refer to: ICache, CacheManager, GetCache, ConnectionOptions, ServerInfo, SecurityOptions, and CreateWithCredentials.
  • Add the following Maven dependencies for your Java client application in pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache-->
    <artifactId>ncache-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Import the following packages in your Java client application:
    • import com.alachisoft.ncache.client.*;
    • import com.alachisoft.ncache.runtime.exceptions.*;
  • The cache must be running.
  • Make sure that the data being added is serializable.
  • For API details, refer to: Cache, CacheManager, getCache, CacheConnectionOptions, TimeSpan, setRetryInterval, setEnableKeepAlive, setConnectionRetries, setKeepAliveInterval, setLoadBalance, setIsolationLevel, Credentials, setUserCredentials.
  • Install the following packages in your Python client application:
    • NCache: ncache-client
  • Import the following packages in your application:
    • from ncache.client import*
  • The cache must be running.
  • Make sure that the data being added is serializable.
  • For API details, refer to: Cache, CacheManager, get_cache, CacheConnectionOptions, set_retry_interval, set_connection_retries, set_keep_alive_interval, set_load_balance, set_isolation_level, Credentials, set_user_credentials.
  • Install and include the following module in your Node.js client application:
    • NCache: ncache-client
  • Include the following class in your application:
    • Cache
  • The cache must be running.
  • Make sure that the data being added is serializable.
  • For API details, refer to: Cache, CacheManager, getCache, CacheConnectionOptions, setRetryInterval, TimeSpan, setKeepAliveInterval, setLoadBalance, setIsolationLevel, Credentials, setUserCredentials.
  • Install either of the following NuGet packages in your .NET client application:
    • NCache: Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Include the Alachisoft.NCache.Web.Caching and Alachisoft.NCache.Web.Security namespaces in your application.
  • To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.

How to Connect to Single Cache

NCache provides an ICache interface to get an instance of NCache’s cache. Moreover, the CacheManager class lets you connect to the cache instance via the GetCache method. The following example connects to a cache named defaultCache which is in running state.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
try
{
  // Specify the cache name
  string cacheName = "defaultCache";

  // Connect to cache
  ICache cache = CacheManager.GetCache(cacheName);
}
catch (OperationFailedException ex)
{
      // NCache specific exception
      if (ex.ErrorCode == NCacheErrorCodes.NO_SERVER_AVAILABLE)
      {
            // Make sure NCache Service and cache is running
      }
      else
      {
            // Exception can occur due to:
            // Connection Failures
            // Operation Timeout
            // Operation performed during state transfer
      }
}
catch (ConfigurationException ex)
{
      if(ex.ErrorCode == NCacheErrorCodes.SERVER_INFO_NOT_FOUND)
      {
            // The client must have server information
      }
}
catch (Exception ex)
{
      // Any generic exception like ArgumentNullException or ArgumentException
      // Argument exception occurs in case of empty string name
}
try
{
  // Specify the cache name
  String cacheName = "defaultCache";

  // Connect to cache
  Cache cache = CacheManager.getCache(cacheName);

}
catch (OperationFailedException exception)
{

  // NCache specific exception
  if (exception.getErrorCode() == NCacheErrorCodes.NO_SERVER_AVAILABLE)
  {
        // Make sure NCache service and cache are running
  } else
  {
        // Exception can occur due to:
        // Connection failures
        // Operation timeout
        // Operation performed during state transfer
  }
}
catch (ConfigurationException exception)
{
if (exception.getErrorCode() == NCacheErrorCodes.SERVER_INFO_NOT_FOUND)
{
      // The client must have server information
}
}
catch (Exception exception)
{
      // Any generic exception
}
try:
    # Specify the cache name
    cache_name = "defaultCache"

    # Connect to cache
    cache = ncache.CacheManager.get_cache(cache_name)

except Exception as error:
    # Handle any exceptions
    print(f"An error occurred: {error}")
try
{
  // Specify the cache name
  let cacheName = "defaultCache";

  // Connect to cache
  let cache = await ncache.CacheManager.getCache(cacheName);

} catch (error)
{
    // Handle any exceptions
}
// Using NCache 4.9.1

try
{
  // Specify the cache name
  string cacheName = "defaultCache";

  // Connect to cache
  cache = NCache.InitializeCache(cacheName);
}
catch (OperationFailedException ex)
{
      // NCache specific exception
      if (ex.ErrorCode == NCacheErrorCodes.NO_SERVER_AVAILABLE)
      {
            // Make sure NCache Service and cache is running
      }
      else
      {
            // Exception can occur due to:
            // Connection Failures
            // Operation Timeout
            // Operation performed during state transfer
      }
}
catch (ConfigurationException ex)
{
      if(ex.ErrorCode == NCacheErrorCodes.SERVER_INFO_NOT_FOUND)
      {
            // The client must have server information
      }
}
catch (Exception ex)
{
      // Any generic exception like ArgumentNullException or ArgumentException
      // Argument exception occurs in case of empty string name
}
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

How to Connect to Multiple Caches

Using the GetCache method, you can connect to multiple caches within a single application. This will help you manage the data of multiple caches using one application. The following example connects to two caches, defaultCache and defaultClusteredCache from the same client.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Specify cache names
string cacheName1 = "defaultCache";
string cacheName2 = "defaultClusteredCache";

// Connect to the caches
ICache cache1 = CacheManager.GetCache(cacheName1);
ICache cache2 = CacheManager.GetCache(cacheName2);
// Specify cache names
String cacheName1 = "defaultCache";
String cacheName2 = "defaultClusteredCache";

// Connect to the caches
Cache cache1 = CacheManager.getCache(cacheName1);
Cache cache2 = CacheManager.getCache(cacheName2);
# Specify cache names
cache_name_1 = "defaultCache"
cache_name_2 = "defaultClusteredCache"

# Connect to the caches
cache_1 = ncache.CacheManager.get_cache(cache_name_1)
cache_2 = ncache.CacheManager.get_cache(cache_name_2)
// Specify cache names
let cacheName1 = "defaultCache";
let cacheName2 = "defaultClusteredCache";

// Connect to the caches
let cache1 = await ncache.CacheManager.getCache(cacheName1);
let cache2 = await ncache.CacheManager.getCache(cacheName2);
// Using NCache 4.9.1
// Specify cache names
string cacheName1 = "defaultCache";
string cacheName2 = "defaultClusteredCache";

// Connect to the caches
Cache cache1 = NCache.InitializeCache(cacheName1);
Cache cache2 = NCache.InitializeCache(cacheName2);

How to Connect to Cache Using ConnectionOptions

Use the .NET ConnectionOptions class to provide application-specific connection information, such as server endpoints, security credentials, and the local binding IP. Connection tuning, client logging, and client cache settings are configured on the cache server.

  • .NET
// Specify the cache name
string cacheName = "defaultCache";

// Configure the cache server endpoints
ConnectionOptions options = new ConnectionOptions();
options.Servers = new List<ServerInfo>
{
    new ServerInfo("20.200.20.11", 9800),
    new ServerInfo("20.200.20.12", 9800)
};

// Connect to the cache
ICache cache = CacheManager.GetCache(cacheName, options);
Note

The ConnectionOptions class and overload shown above apply to the .NET API in NCache 5.3.8. The Java, Python, and Node.js APIs may use different option classes and methods; refer to their respective API references for supported signatures.

How to Connect to Cache Through a Load Balancer

When a client connects through a load balancer, specify its address as a server endpoint and identify it as a load balancer using ServerInfo.IsLoadBalancer.

  • .NET
ConnectionOptions options = new ConnectionOptions();
options.Servers = new List<ServerInfo>
{
    new ServerInfo(true, "20.200.20.11", 9800)
};

ICache cache = CacheManager.GetCache("defaultCache", options);
Note

For details, see Load Balancer.

How to Connect to Cache Using Security API

You can also use the SecurityOptions class to configure authentication for cache connections, either by enabling gMSA-based password-less authentication or by providing explicit user credentials.

Connect using gMSA Security

NCache allows you to use Group Managed Service Accounts (gMSA) for secure, password-less authentication when connecting to the cache. By enabling gMSA authentication, the client application uses the machine’s configured gMSA identity, which is managed by Active Directory.

Important

Please note that the client application must also run under the configured gMSA user.

The following example demonstrates how to connect to the cache using gMSA-based authentication with the CreateWithGMSA method.

  • .NET
string cacheName = "defaultCache";

var connectionOptions = new ConnectionOptions();

// If the user wants to use GMSA, they can set the Security property to use GMSA credentials
connectionOptions.Security = SecurityOptions.CreateWithGMSA();

ICache cache = CacheManager.GetCache(cacheName, connectionOptions);

Connect using CreateWithCredentials API

This example shows how to connect to the cache using the CreateWithCredentials method for username/password authentication.

  • .NET
string cacheName = "defaultCache";

var connectionOptions = new ConnectionOptions();

// If the user wants to use username/password credentials, they can set the Security property to use those credentials
connectionOptions.Security = SecurityOptions.CreateWithCredentials("your-username", "your-password");

ICache cache = CacheManager.GetCache(cacheName, connectionOptions);

Initialize an InProc Local Cache Using API

You can initialize a Local Cache as InProc programmatically by setting the Mode property of ConnectionOptions to InProc and passing the configured options to CacheManager.GetCache(). This allows the cache to run within the application process.

The following example initializes a Local Cache named defaultCache as InProc.

// Specify the cache name
string cacheName = "defaultCache";

// Configure the cache to run as InProc
ConnectionOptions options = new ConnectionOptions();
options.Mode = IsolationLevel.InProc;

// Initialize the InProc Local Cache
ICache cache = CacheManager.GetCache(cacheName, options);
Note

This method applies to a Local Cache. Setting Mode to InProc causes the cache to run within the application process.

How to Connect to Clustered and Client Cache

A client cache is configured on the cache server and its settings are supplied automatically when the client connects. Applications connect to the clustered cache using GetCache; they do not need to initialize the client cache through a separate GetCache overload.

  • .NET
// Connect to the clustered cache. The server supplies client cache settings.
ICache cache = CacheManager.GetCache("defaultClusteredCache");

To bypass the configured client cache for a particular connection, set IgnoreClientCache to true:

ConnectionOptions options = new ConnectionOptions();
options.IgnoreClientCache = true;

ICache cache = CacheManager.GetCache("defaultClusteredCache", options);

Troubleshooting

Port is Not Accessible

Sometimes clients may be unable to connect to a cache due to your firewall configurations.

Workaround: Use the details in our installation guide to change your firewall settings.

Workaround

If %NCHOME% is not set, follow the steps below to set the environment variable for it:

  • Right-click on the Start button and select System.
  • In the right pane, click on Advanced System Settings.
  • In the System Properties window, go to the Advanced tab and click on the Environment Variables button.
  • In the Environment Variables window, under System Variables, click on New.
  • For Variable Name, enter %NCHOME%.
  • For Variable Value, enter C:\Program Files\NCache.
  • Click OK.
  • Now to update the system path in the same Environment Variables window, find the Path variable and click Edit.
  • In the Edit Environment Variable window, click New and add %NCHOME%\bin to the list. This makes sure that the tools are available globally.
  • Click OK to close each of the windows.

No server available to process request

Sometimes a client may be unable to connect to the cache because the client/server Port is blocked by a firewall.

Workaround

Make sure that the client/server port (at which NCache Service starts and accepts different client connections) is not blocked by a firewall. The default value of this port is '9800'. You can change the default value from Alachisoft.NCache.Service.exe.config or Alachisoft.NCache.Service.dll.config file.

Unable to communicate with server node

Cluster nodes may also be unable to communicate with each other because of cluster ports being blocked by a firewall.

Error: "Unable to communicate with server node"

Workaround

See if your firewall is allowing the client/server and cluster port. A cluster port is a port at which nodes in a cluster communicate. You can change the default value of these ports from NCache Management Center. If you have specified a port range in the NCache Management Center, unblock all ports in the 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

Step 1: Changes on Server-side

Go to the service configuration file:

  • Windows: Alachisoft.NCache.Service.dll.config located in %NCHOME%\bin\service
  • Linux: Alachisoft.NCache.Daemon.dll.config located in /opt/ncache/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 cannot 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 of 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 the bulk of events is fired even in case the bulk count does not reach the EventBulkCount that the user has specified. The 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.

Step 2: Changes on Client-side

Please make the following changes in your App.config/Web.config file:

<configuration>
    <appSettings>
          <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 the 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 the client-side.

  • NumberofEventProcessingThreads: When the user has configured events to be fired synchronously, this flag is used to specify the number of threads that will process these events on the client-side. A very large value can cause performance issues.

See Also

.NET: Alachisoft.NCache.Client namespace.
Java: com.alachisoft.ncache.client namespace.
Python: ncache.client module.
Node.js: Cache class.

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top