Cookie Consent by Free Privacy Policy Generator Using NCache as a Spring Caching Provider

Using NCache as a Spring Caching Provider

Today we are going to go over how you can use NCache as a spring caching provider. Please note that NCache is a popular distributed cache that supports both Java and .NET applications.

NCache Architecture

Here is how NCache is typically deployed in an enterprise environment. Notice a separate caching tier that consists of a cache server and your application, the tier is called the cache clients.

NCache Deployment in an Enterprise Environment
NCache Deployment in an Enterprise Environment

NCache Setup for Spring

Now let's dive into using NCache with spring. But before we move on to the steps, I want to show you what my current project setup looks like. So I have here a spring boot application. We have three layers, a controller, repository, and service layer. I have a UI connected to this as well. And I have a database setup of MySQL. So as of now, I do not have caching enabled, and nor do I have NCache integrated into my application as of now. So we're going to cover those steps and show you how it's all done. Let's move on to the setup now.

  • Step 1: Add NCache Spring Maven Dependency
  • Step 2: Specify Cache Configurations in ncache-spring.xml
  • Step 3: Configure Spring Beans
    • Java based configuration (recommended)
    • XML based configuration (optional)

Add NCache Spring Maven Dependency

The first thing you want to do is add this NCache spring maven dependency into our pom.xml file. Now, if you want to know where you can find this dependency from, I'm going to go over to the Alachisoft's website, and I'm going to go into the Docs section and look for the Programmer's Guide. From here, we're going to go into the Spring Integration. Going to go on this section over here (Configure Generic Provider). And this is the dependency we want to copy.

<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <artifactId>ncache-spring</artifactId>
    <version>x.x.x</version>
</dependency>

So, I'm just going to paste this over here. As of now, the latest version we have is 5.3.6. But just to double check, I'm going to check the Maven central repository.

So, I'm going to go into developers and Java integrations. This will point me to the Maven central repository. And yeah, we can see the latest version here is 5.3.6. So, I'm going to reload these Maven changes. And we can see we're downloading the dependencies here. If I quickly go into my libraries, I can see that the NCache libraries have been downloaded. So, as of now, we're good to go.

Specify Cache Configurations in ncache-spring.xml

The next step is to specify the cache configuration in this file over here. So we're going to create that right now under the resources folder, with the name of ncache-spring.xml. So this is just an XML file where we are going to specify our cache configuration of NCache. And let me show where you can find the XML setup as well.

So if you scroll a little bit below on the same section over here, configure cache policies in ncache-spring.xml, we're just going to copy this since I already have a cache configured with the name of demoCache. And you can also specify these cache options over here, such as the priority level, expiration type, which can be absolute or sliding, and the expiration period. So, let's paste this over here.

<application-config default-cache-name="demoCache">
    <caches>
        <cache name="demoCache" ncacheid-instance="democache" priority="normal" expiration-type="absolute" expiration-period="300"/>
    </caches>
</application-config>

NCache Management Center

Let me really quickly show what my NCache Management Center looks like. So, as of now, my cache is not started. You'll notice I already have a cache configured with the name of "demoCache". So, my NCache is deployed on a docker instance, and we typically use Linux images in our docker file so that's why it says Linux over here, and we are using a single server node.

So before we start this, I just want to check that my container is running. Let me just write my password again over there. Okay, so our container is up and running.

Container Running

I'm going to start the cache now. Of course, in your environment, you can configure many servers. For this example, we're just going to use one. The NCache is now up and running.

Container Running

Configure Spring Beans

Java based configuration (recommended)

So, we can move forward to the next step, which is to configure the Spring Beans. Now, this can be done in two ways. One is the Java based configuration, where we use annotations, and this is also what I'm going to use in my project. The second one is the XML based configuration, where we define an XML file and the beans inside it. Of course, that depends on how your current setup is. So let me first show you how we can use the Java based configuration.

First things first, we're going to annotate our main entry point application with @EnableCaching. So, to reiterate, this has to be done regardless of which configuration method you're using. And now we're going to create a new file. The name of the file does not matter, as long as you annotate the file with @Configuration over here.

Okay, we need to define a single bean method at this point. And if we navigate to the same setup guide, we will see there is a bean over here with the name of cache manager. We're just going to copy this over here and paste it there.

@Configuration
class CachingConfiguration {
    @Bean
    public CacheManager cacheManager() {
        String resource = Path.of(System.getenv("NCHOME"), "config/ncache-spring.xml").toString();

        SpringConfigurationManager springConfigurationManager = new SpringConfigurationManager();
        springConfigurationManager.setConfigFile(resource);

        NCacheCacheManager cacheManager = new NCacheCacheManager();
        cacheManager.setSpringConfigurationManager(springConfigurationManager);

        return cacheManager;
    }
}

Okay, let me just import all of these dependencies before we move forward. Okay, notice we are passing in the path to our ncache-spring.xml file. Let me just correct this so we get the direct path instead. So I'm going to copy this from the source folder. So that is pretty much all we need to do for the Java based annotation configuration. I'm also going to show how you can do this in XML.

XML based configuration (optional)

In the case we are doing XML, you do not need to define the CacheConfig class. You just simply need to define your beans over here in beans.xml. We're going to need to define two beans. One with the name of "cacheManager".

<bean id="cacheManager" class="com.alachisoft.integrations.spring.NCacheCacheManager">
    <property name="springConfigurationManager" ref="NCacheConfigurationManager"/>
    <property name="logFilePath" value="C:\Program Files\NCache\log-files\CustomerDBSpringLogs"/>
</bean>

And the second one is going to be the "NCacheConfigurationManager".

<bean id="NCacheConfigurationManager" class="com.alachisoft.integrations.spring.configuration.SpringConfigurationManager">
        <property name="configFile" value="ncache-spring.xml">
</bean>

So as you'll notice, these beans are already being defined in our cache configuration class. It's just a matter of preference of what you want to use. If we actually click into these classes, you'll notice this is NCache code that is responsible for the integration in the first place.

Okay. So let's just comment out the bean declaration we made, since we're sticking to the Java annotations base. And that is our integration setup complete. Now we can move forward to the next step, which is to actually annotate the caching methods.

Annotate the Caching Methods

Cache Get

So there's three methods we're going to annotate in my project. One is for the Cache Get, Cache Put, and the Cache Evict operations. So let's show what that's going to look like. Now I'm going to do this in the service layer my class. We're going to go over here. In the case of get product, I'm going to do @Cacheable. I'm going to pass in the name of my cache, which is "demoCache". And, I'm also going to give in the key value here, which is going to be the #id. And id in this case is the parameter in our method, as you can see here. Also, one more condition I'm going to add over here is to say that unless the result is equal to null. And this basically means that if the result value is null, do not save it into the cache. This will prevent null pointer errors.

@Cacheable(value = "demoCache", key = "#id", unless = "#result==null")

Cache Put

Let's repeat this for the rest of the methods. In this case, it's going to be @CachePut. We're going to remove this over here. Notice how the method parameter over here is actually product. So in this case, what we're going to do is we're going to pass in a reference to the product ID within the product object. If you go into the product class, you'll see I have productID over here. And that's why we do this.

@CachePut(value = "demoCache", key="#product.productID")

Cache Evict

And lastly, we're going to do @CacheEvict over here, or deletion.

@CacheEvict(value = "demoCache", key = "#id")

And since we are passing in an ID over here, we're going to leave this as it is. So if you find the declaration of the cache name to be repetitive, one more thing we can do is to annotate our class with @CacheConfig and pass in the cache name over here.

@CacheConfig(cacheNames = "demoCache")

And because we're doing this, we can remove this declaration from here in all of our methods.

Spring Demo

Before we actually start the application, I just want to check my database. Make sure there's no data in it. Okay. And also I'm going to check my NCache cluster and make sure there's also no data in it. So we're going to go on statistics over here. Our count is zero as of now. So let's start our application. And hopefully there are no errors over here. The application is up and running. So what I'm going to do is I'm going to try and open this side by side with my Spring application, just so we can see the operations happen in real time. So I'm going to add three products first. Keep in mind the first request takes a little bit of time, just because we try to initialize the cache. And you can see the count goes up over here. Let's add two more. And last one. As you can see, the cache count is going up. And we're going to check the database as well, to make sure the data is inserted.

Product Added at runtime.

So, what we're seeing is the cache data is being inserted into the cache and the database. If I try to get ID number two, it should give me oranges. And if I try to delete ID number three, this should reflect both in the cache, as you can see, and in the database. As you can see, the object has been deleted. That is it for our demonstration.

Schedule a Demo

Please contact us to schedule a demo to learn more about NCache architecture, its features and strategy, or how you can incorporate NCache into your application. Thank you.

What to Do Next?

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