Hazelcast: Setup Using Java
Join the DZone community and get the full member experience.
Join For FreeThank you all for reading my last article, Hazelcast: Introduction and Clustering, which gives you an introduction about the caching and clustering technologies. In this, we will be moving with a Spring Boot project to set up a simple Hazelcast server and client.
Let's start by adding the dependency to our "pom.xml" file or "build.gradle" depending on the type of build tool.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
compile group: 'org.springframework', name: 'spring-web', version: '5.2.6.RELEASE'
compile('com.hazelcast:hazelcast:3.7.5')
compile('com.hazelcast:hazelcast-client:3.7.5')
}
com.hazelcast:hazelcast is the core Hazelcast jar adds the functions regarding the utilities such as IMap, Hazelcast instance, etc. hazelcast-client is the java native library to create a hazelcast client to fetch and put the data in the cache.
Configurations:
We can configure Hazelcast either using XML or using java. Since we are using spring boot let's move ahead with the second approach.
xxxxxxxxxx
public class HazelcastConfig {
public Config configuration(){
Config config = new Config();
config.setInstanceName("hazelcast-instance");
MapConfig mapConfig= new MapConfig();
mapConfig.setName("configuration");
mapConfig.setMaxSizeConfig(new MaxSizeConfig(200, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE));
mapConfig.setEvictionPolicy(EvictionPolicy.LRU);
mapConfig.setTimeToLiveSeconds(-1);
config.addMapConfig(mapConfig);
return config;
}
}
Controller:
After configuring the Hazelcast let's add a controller to manipulate data (perform CRUD) in the cluster.
xxxxxxxxxx
import org.springframework.web.bind.annotation.*;
/**
* @author Dheeraj Gupta
*/
"/v1/data") (
public class HazelcastCRUDController {
private static final Logger LOGGER = LogManager.getLogger(HazelcastCRUDController.class);
private HazelcastService hazelcastService;
value = "/create") (
public String createData( String key, String value) {
hazelcastService.createData(key, value);
return "Success";
}
value = "/getByKey") (
public String getDataByKey( String key) {
return hazelcastService.getDataByKey(key);
}
value = "/get") (
public IMap<String, String> getData() {
return hazelcastService.getData();
}
value = "/update") (
public String updateData( String key, String value) {
hazelcastService.update(key, value);
return "Success";
}
value = "/delete") (
public String deleteData( String key) {
hazelcastService.deleteData(key);
return "Success";
}
Service Layer:
Here we will add the HazelcastInstance interface which helps to perform CRUD in the Hazelcast cache.
xxxxxxxxxx
/**
* @author Dheeraj Gupta
*/
public class HazelcastServiceImpl implements HazelcastService {
private final HazelcastInstance hazelcastInstance;
HazelcastServiceImpl(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
public String createData(String key, String value) {
IMap<String, String> map = hazelcastInstance.getMap("my-map");
map.put(key, value);
return "Data is stored.";
}
public String getDataByKey(String key) {
IMap<String, String> map = hazelcastInstance.getMap("my-map");
return map.get(key);
}
public IMap<String, String> getData() {
return hazelcastInstance.getMap("my-map");
}
public String update(String key, String value) {
IMap<String, String> map = hazelcastInstance.getMap("my-map");
map.set(key, value);
return "Data is stored.";
}
public String deleteData(String key) {
IMap<String, String> map = hazelcastInstance.getMap("my-map");
return map.remove(key);
}
Utilities (optional):
In this project, I've also added to standalone utilities that can create a Hazelcast server and a Hazelcast client when you run them by themselves.
Hazelcast Server:
xxxxxxxxxx
/**
* @author Dheeraj Gupta
*/
public class Server {
private static final Logger LOGGER = LogManager.getLogger(Server.class);
private Environment environment;
public static void main(String[] args) {
HazelcastInstance instance = Hazelcast.newHazelcastInstance();
Map<Long, String> map = instance.getMap("elements");
IdGenerator idGenerator = instance.getIdGenerator("id");
for (int i = 0; i < 10; i++) {
map.put(idGenerator.newId(), "values"+i);
}
LOGGER.info("Map Components" , map);
}
}
You can run this class multiple to create multiple nodes. These nodes will automatically join themselves and form a cluster.
Hazelcast Client:
This is a standalone utility class to fetch data from the cluster.
xxxxxxxxxx
import java.util.Map;
/**
* @author Dheeraj Gupta
*/
public class Client {
private static final Logger LOGGER = LogManager.getLogger(Client.class);
public static void main(String[] args) {
ClientConfig clientConfig = new ClientConfig();
clientConfig.getGroupConfig().setName("dev");
clientConfig.getGroupConfig().setPassword("dev-pass");
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
IMap<Long, String> map = client.getMap("elements");
for (Map.Entry<Long, String> entry : map.entrySet()) {
LOGGER.info(String.format("Key: %d, Value: %s", entry.getKey(), entry.getValue()));
}
}
}
Configuring Network:
Hazelcast by default uses multicast to discover nodes in a cluster. We can also configure the discovery of our environment by TCP/IP. We can set up the ports and add machine members programmatically. Hazelcast by default books 100 ports for itself starting from 5701. In this file, we can also add the number of nodes we want to create and cluster do not reserve all the ports. In this project, I have used more of the default network configuration and did not configure this.
Our Hazelcast cluster and client are ready. In the above project, while I use spring boot configuration and controller to create and doing CRUD on cache, I also created some utilities to create standalone java classes to create Hazelcast nodes and clients, so that Spring dependency could be lowered.
Again you can find this code at my Github repo: https://github.com/dheerajgupta217/hazelcast-setup
In the next article, Hazelcast Mancenter: Manage your cache, we will be looking into the Hazelcast Management center to manipulate and read caches or maps.
Published at DZone with permission of Dheeraj Gupta. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments