{{announcement.body}}
{{announcement.title}}

Hazelcast: Setup Using Java

DZone 's Guide to

Hazelcast: Setup Using Java

This article defines setting up Hazelcast server and client. Here,Spring is used for performing CRUD and java utilities are standalone classes for nodes set-up.

· Java Zone ·
Free Resource

Thank 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.

Java
 




x


 
1
dependencies {
2
    implementation 'org.springframework.boot:spring-boot-starter'
3
    compile group: 'org.springframework', name: 'spring-web', version: '5.2.6.RELEASE'
4
    compile('com.hazelcast:hazelcast:3.7.5')
5
    compile('com.hazelcast:hazelcast-client:3.7.5')
6
}



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.

Java
 




xxxxxxxxxx
1
15


 
1
@Configuration
2
public class HazelcastConfig {
3
    @Bean
4
    public Config configuration(){
5
        Config config = new Config();
6
        config.setInstanceName("hazelcast-instance");
7
        MapConfig mapConfig= new MapConfig();
8
        mapConfig.setName("configuration");
9
        mapConfig.setMaxSizeConfig(new MaxSizeConfig(200, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE));
10
        mapConfig.setEvictionPolicy(EvictionPolicy.LRU);
11
        mapConfig.setTimeToLiveSeconds(-1);
12
        config.addMapConfig(mapConfig);
13
        return config;
14
    }
15
}



Controller:

After configuring the Hazelcast let's add a controller to manipulate data (perform CRUD) in the cluster.

Java
 




xxxxxxxxxx
1
39


 
1
import org.springframework.web.bind.annotation.*;
2
 
          
3
/**
4
 * @author Dheeraj Gupta
5
 */
6
 
          
7
@RestController
8
@RequestMapping("/v1/data")
9
public class HazelcastCRUDController {
10
    private static final Logger LOGGER = LogManager.getLogger(HazelcastCRUDController.class);
11
 
          
12
    @Autowired
13
    private HazelcastService hazelcastService;
14
 
          
15
    @PostMapping(value = "/create")
16
    public String createData(@RequestParam String key, @RequestParam String value) {
17
        hazelcastService.createData(key, value);
18
        return "Success";
19
    }
20
 
          
21
    @GetMapping(value = "/getByKey")
22
    public String getDataByKey(@RequestParam String key) {
23
        return hazelcastService.getDataByKey(key);
24
    }
25
 
          
26
    @GetMapping(value = "/get")
27
    public IMap<String, String> getData() {
28
        return hazelcastService.getData();
29
    }
30
    @PutMapping(value = "/update")
31
    public String updateData(@RequestParam String key, @RequestParam String value) {
32
        hazelcastService.update(key, value);
33
        return "Success";
34
    }
35
    @DeleteMapping(value = "/delete")
36
    public String deleteData(@RequestParam String key) {
37
        hazelcastService.deleteData(key);
38
        return "Success";
39
    }



Service Layer:

Here we will add the HazelcastInstance interface which helps to perform CRUD in the Hazelcast cache.

Java
 




xxxxxxxxxx
1
39


1
/**
2
 * @author Dheeraj Gupta
3
 */
4
@Service
5
public class HazelcastServiceImpl implements HazelcastService {
6
    private final HazelcastInstance hazelcastInstance;
7
 
          
8
    @Autowired
9
    HazelcastServiceImpl(HazelcastInstance hazelcastInstance) {
10
        this.hazelcastInstance = hazelcastInstance;
11
    }
12
    @Override
13
    public String createData(String key, String value) {
14
        IMap<String, String> map = hazelcastInstance.getMap("my-map");
15
        map.put(key, value);
16
        return "Data is stored.";
17
    }
18
 
          
19
    @Override
20
    public String getDataByKey(String key) {
21
        IMap<String, String> map = hazelcastInstance.getMap("my-map");
22
        return map.get(key);
23
    }
24
 
          
25
    @Override
26
    public IMap<String, String> getData() {
27
        return hazelcastInstance.getMap("my-map");
28
    }
29
    @Override
30
    public String update(String key, String value) {
31
        IMap<String, String> map = hazelcastInstance.getMap("my-map");
32
        map.set(key, value);
33
        return "Data is stored.";
34
    }
35
    @Override
36
    public String deleteData(String key) {
37
        IMap<String, String> map = hazelcastInstance.getMap("my-map");
38
        return map.remove(key);
39
    }



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:

Java
 




xxxxxxxxxx
1
20


1
/**
2
 * @author Dheeraj Gupta
3
 */
4
public class Server {
5
 
          
6
    private static final Logger LOGGER = LogManager.getLogger(Server.class);
7
 
          
8
    @Autowired
9
    private Environment environment;
10
 
          
11
    public static void main(String[] args) {
12
        HazelcastInstance instance = Hazelcast.newHazelcastInstance();
13
        Map<Long, String> map = instance.getMap("elements");
14
        IdGenerator idGenerator = instance.getIdGenerator("id");
15
        for (int i = 0; i < 10; i++) {
16
            map.put(idGenerator.newId(), "values"+i);
17
        }
18
        LOGGER.info("Map Components" , map);
19
    }
20
}



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.

Java
 




xxxxxxxxxx
1
20


 
1
import java.util.Map;
2
 
          
3
/**
4
 * @author Dheeraj Gupta
5
 */
6
public class Client {
7
 
          
8
    private static final Logger LOGGER = LogManager.getLogger(Client.class);
9
 
          
10
    public static void main(String[] args) {
11
        ClientConfig clientConfig = new ClientConfig();
12
        clientConfig.getGroupConfig().setName("dev");
13
        clientConfig.getGroupConfig().setPassword("dev-pass");
14
        HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
15
        IMap<Long, String> map = client.getMap("elements");
16
        for (Map.Entry<Long, String> entry : map.entrySet()) {
17
            LOGGER.info(String.format("Key: %d, Value: %s", entry.getKey(), entry.getValue()));
18
        }
19
    }
20
}



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.

Topics:
caching, distributed systems, hazelcast, spring boot

Published at DZone with permission of Dheeraj Gupta . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}