DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • Exploring Hazelcast With Spring Boot
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)

Trending

  • Why Database Migrations Take Months and How to Speed Them Up
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  1. DZone
  2. Coding
  3. Frameworks
  4. Hazelcast: Setup Using Java

Hazelcast: Setup Using Java

By 
Dheeraj Gupta user avatar
Dheeraj Gupta
DZone Core CORE ·
Updated Jun. 18, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
133.6K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Hazelcast Java (programming language) Spring Framework clustering Spring Boot

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

Opinions expressed by DZone contributors are their own.

Related

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • Exploring Hazelcast With Spring Boot
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!