Basic about cache in Apache Ignite

In the previous tutorial, I showed you how to install Apache Ignite. In this tutorial, I will show you the basic steps to use Apache Ignite’s cache function through an example!

First, I will create a Maven project to do this:

Basic about cache in Apache Ignite

with Apache Ignite dependency as follows:

To work with Apache Ignite, you need to start an instance as a node of Apache Ignite. We can have multiple nodes running at the same time, so the data that we save or cache will be distributed to all of our nodes.

Myself is as follows:

Basic about cache in Apache Ignite

Now I will create a class to run the application with main() method in it, I will connect to Apache Ignite and then try to save a text to cache of Apache Ignite!

To connect to the Apache Ignite node that we have already started, you need to initialize IgniteClient object using Ignition class with static startClient() method of this class.

The parameter of the startClient() static method is a ClientConfiguration object. We need to initialize the ClientConfiguration object using a constructor without parameter and configure Apache Ignite’s information as follows:

“localhost:10800” is the information about Apache Ignite which I started above, by default Apache Ignite will run on port 10800!

The value of the parameter in the setAddresses() method is an array of node information of Apache Ignite, so if you have multiple Apache Ignite nodes, you can add their information using this method.

After you initialize the ClientConfiguration object, you can now initialize the IgniteClient object as follows:

I use try-with-resource so that when running out of use, the igniteClient variable will automatically close the connection.

Now let’s try to save a text to the cache of Apache Ignite!

To do this, you need to initialize ClientCache object using the getOrCreateCache() method of IgniteClient object as follows:

The getOrCreateCache() method will automatically create a new cache if it does not already exist. “huongdanjava” is the name of the cache we need to create. Depending on your wishes, please name it accordingly!

We use the ClientCache object to store the value in the cache, specifically as follows:

At this point, we have saved the value to Apache Ignite cache, try taking them:

The entire code will look like this:

The result when running the example above is as follows:

Basic about cache in Apache Ignite

Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment