Java Client
This section provides a deep dive into integrating NCache into your Java applications, covering everything from environment setup to API usage.
Prerequisites
Before proceeding, ensure your environment meets the following requirements:
- Existing Cache: A running cache (e.g.,
demoCache) must already be created on an NCache server. - Java Development Kit (JDK): The recommended is version 17. For all supported Java versions, refer to Supported Java Versions.
- NCache Installation: You must have NCache Enterprise installed on your cache servers. For the client machine, you only need the client libraries.
- Environment Variable: Ensure that the Environment Variable for Java is set. JAVA_HOME should be added to the System Variables and
%JAVA_HOME%should be in the Path. - Cache Connectivity: Ensure network access to the cache servers (IP address and port, typically 9800).
- Data being cached is serializable.
- Exception handling is in place as described in Handling Failures.
Install Client (Optional)
If your application runs on a machine that does not have a full NCache setup, you can install the NCache Client separately.
NCache provides a Windows Installer (.msi) with which you can install NCache through command line silent mode.
Search for Command Prompt on the Windows Start menu. Right-click on the search result Command Prompt, and select Run as Administrator.
You can install either Cache Server, Developer/QA, or Remote Client. For instance, for Remote Client mode, set the
InstallMode=3in the following command:
msiexec.exe /I "C:\NCacheSetupPath\ncache.ent.net.x64.msi" INSTALLMODE=3 /qn
Setup Java Client
Maven Dependencies
- Launch your Java sample application in a Java IDE of your choice. For example, IntelliJ 2019 or above.
Add the following Maven dependency for your Java client application in pom.xml file:
<dependency> <groupId>com.alachisoft.ncache</groupId> <!--for NCache Enterprise--> <artifactId>ncache-client</artifactId> <version>5.3.7</version> </dependency>
Indexing for SQL Searching
If you plan to use SQL-like queries, you must upload a JAR file containing your searchable classes (e.g., Product.class) to the NCache Management Center under Query Indexes. Without this, the server cannot "see" the object fields to filter them.
Note
Please refer to the NCache Downloads page for the latest NCache version.
To add Maven Dependencies for other Java integrations (Java Web Sessions, Hibernate, Spring, Spring Sessions, etc.), please see Adding Maven Dependencies for Java Client documentation.
Code Samples
The following samples demonstrate how to perform core caching operations using the NCache Java API.
Data Caching
Once your environment is set up, you can begin performing caching operations. The following sample demonstrates how to connect to a running cache and add an object.
Please note that your custom objects (like the Product class) must implement the java.io.Serializable interface.
import com.alachisoft.ncache.client.*;
import java.io.Serializable;
// Connect to cache
Cache cache = CacheManager.getCache("demoCache");
// Create your data object
Product product = new Product(1005, "Laptop", 1500, "Electronics");
// Wrap the object in a CacheItem
CacheItem cacheItem = new CacheItem(product);
// Add to Cache
cache.add("1009", cacheItem);
System.out.println("Item 1009 successfully added to demoCache.");
cache.close();
// Product class must be public and Serializable
class Product implements Serializable
{
private int id;
private String name;
private double price;
private String category;
public Product(int id, String name, double price, String category)
{
this.id = id; this.name = name; this.price = price; this.category = category;
}
}
For details on basic cache functionality, refer to the Basic Operations documentation.
Tags
Tags allow you to categorize your data with meaningful keywords, making it easier to retrieve or manage related items in groups. The following code associates searchable keywords (Tags) to a CacheItem as metadata before storing it in the cluster. It then uses the getSearchService() to perform a grouped lookup, retrieving multiple related objects at once without needing their individual keys.
...
import com.alachisoft.ncache.runtime.caching.Tag;
import java.util.*;
// Create an item with multiple labels
Product p = new Product(1002, "Phone", 800, "Electronics");
CacheItem item = new CacheItem(p);
// Assign tags
item.setTags(Arrays.asList(new Tag("Electronics"), new Tag("Mobile")));
cache.insert("1002", item);
// Retrieve all objects sharing a specific tag
Map<String, Product> results = cache.getSearchService().getByTag(new Tag("Mobile"));
System.out.println("Items found with tag 'Mobile': " + results.size());
...
For more information on using tags, please see Tags documentation.
SQL
NCache provides an efficient, Object-Relational querying mechanism that lets you retrieve cached data based on specified criteria and obtain the result using standard SQL-like syntax. The following code executes a parameterized SQL-like query on the cache to retrieve objects matching specific criteria (price and category).
...
import com.alachisoft.ncache.runtime.caching.*;
// IMPORTANT: Ensure 'price' and 'category' are indexed in the Management Center
// Use $VALUE$ to return the entire object, or specify fields like 'this.name'
String query = "SELECT $VALUE$ FROM org.example.Product WHERE price > ? AND category = ?";
QueryCommand sqlCommand = new QueryCommand(query);
sqlCommand.getParameters().put("price", 500);
sqlCommand.getParameters().put("category", "Electronics");
CacheReader reader = cache.getSearchService().executeReader(sqlCommand);
System.out.println("Search results for Electronics > $500:");
while (reader.read())
{
Product found = reader.getValue("$VALUE$", Product.class);
System.out.println(" - Found: " + found.getName() + " ($" + found.getPrice() + ")");
}
...
// Class Getters are required for NCache Indexing service to read field values
public double getPrice() { return price; }
public String getCategory() { return category; }
To learn more about SQL Queries, please see SQL Query documentation.
Events
NCache provides an event-driven model that allows client applications to react to changes within the cache. This sample demonstrates Item-Level Events, which allow you to monitor specific keys for updates or removals. The following sample registers an item-level event listener that triggers a callback when the item is updated.
...
import com.alachisoft.ncache.runtime.events.*;
import java.util.EnumSet;
// Add an item first, because the key must already exist
Product product = new Product(1005, "Laptop", 1500, "Electronics");
String key = "Product:1005";
cache.add(key, new CacheItem(product));
// Register the listener
CacheDataModificationListener dataNotificationListener =
new CacheDataModificationListenerImpl();
// Register item-level notifications for update operation
cache.getMessagingService().addCacheNotificationListener(
key,
dataNotificationListener,
EnumSet.of(EventType.ItemUpdated),
EventDataFilter.DataWithMetadata
);
System.out.println("Item-level event notifications registered successfully.");
// Update the item to trigger Item Updated event
product.setPrice(1750);
cache.insert(key, new CacheItem(product));
private static class CacheDataModificationListenerImpl
implements CacheDataModificationListener {
@Override
public void onCacheDataModified(String key, CacheEventArg args) {
switch (args.getEventType()) {
case ItemUpdated:
System.out.println(
"Item with key '" + key + "' updated in cache '"
+ args.getCacheName() + "'."
);
if (args.getItem() != null) {
Product p = args.getItem().getValue(Product.class);
System.out.println(" >> Updated product: " + p.getName()
+ ", Price: " + p.getPrice()
);
}
break;
}
}
}
...
To learn more about Events, please see Event Notifications in Cache documentation.
Important
After running the application or performing cache operations, NCache generates log files that can be used for monitoring and troubleshooting. By default, the log files are generated at the following location: %NCHOME%\log-files. Log file locations may vary if a custom installation directory was selected during NCache setup.
Note
For more details on using NCache, please refer to the Developer's Guide.
See Also
NCache Installation
NCache Developer's Guide
NCache Command Line Interface