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
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Working With Spring Boot and Hazelcast (Distributed Cache)
  • Embracing Reactive Programming With Spring WebFlux
  • Building Real-Time Applications to Process Wikimedia Streams Using Kafka and Hazelcast
  • Spring Boot Annotations: Behind the Scenes and the Self-Invocation Problem

Trending

  • Harnessing the Power of In-Memory Databases: Unleashing Real-Time Data Processing
  • New Free Tool From Contrast Security Makes API Security Testing Fast and Easy
  • Best Practices for Writing Clean Java Code
  • Leveraging FastAPI for Building Secure and High-Performance Banking APIs
  1. DZone
  2. Coding
  3. Frameworks
  4. Configuring Hazelcast within Spring Context

Configuring Hazelcast within Spring Context

Roshan Thomas user avatar by
Roshan Thomas
·
Jan. 30, 15 · Tutorial
Like (3)
Save
Tweet
Share
25.74K Views

Join the DZone community and get the full member experience.

Join For Free

At first we need to declare an instance of Hazelcast within the Spring context using default spring bean namespace. To integrate Hazelcast with Spring we need either hazelcast-spring.jar or hazelcast-all.jar in the classpath. 

<bean id="instance" class="com.hazelcast.core.Hazelcast" factory-method="newHazelcastInstance">
    <constructor-arg>
        <bean class="com.hazelcast.config.Config">
            <property name="groupConfig">
                <bean class="com.hazelcast.config.GroupConfig">
                    <property name="name" value="dev"/>
                    <property name="password" value="pwd"/>
                </bean>
            </property>
            <!-- and so on ... -->
        </bean>
    </constructor-arg>
</bean>

<bean id="map" factory-bean="instance" factory-method="getMap">
    <constructor-arg value="map"/>
</bean>

We need Spring version 2.5 or greater for hazelcast integration. Since hazelcast version 1.9.1, we have hazelcast namespace to configure in the Spring context file. Namespace (hz) given below.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:hz="http://www.hazelcast.com/schema/spring"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.hazelcast.com/schema/spring
http://www.hazelcast.com/schema/spring/hazelcast-spring-3.0.xsd">


After configuring the hazelcast instance in spring context file, we need to create  hazelcast.xml file which will be placed in the classpath. Sample file given below.

<?xml version="1.0" encoding="UTF-8"?>

<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-3.3.xsd"
           xmlns="http://www.hazelcast.com/schema/config"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <group>
        <name>dev</name>
        <password>dev</password>
    </group>
    <management-center enabled="true">http://localhost:8080/mancenter-3.3.3</management-center>
    <network>
        <port auto-increment="true" port-count="100">5701</port>
        <outbound-ports>
            <!--
            Allowed port range when connecting to other nodes.
            0 or * means use system provided port.
            -->
            <ports>0</ports>
        </outbound-ports>
        <join>
            <multicast enabled="true">
                <multicast-group>224.2.2.3</multicast-group>
                <multicast-port>54327</multicast-port>
            </multicast>
            <tcp-ip enabled="false">
                <interface>127.0.0.1</interface>
            </tcp-ip>
        </join>

    </network>
    <partition-group enabled="false"/>

    <map name="CustomerMap">

        <in-memory-format>BINARY</in-memory-format>

        <backup-count>1</backup-count>

        <async-backup-count>1</async-backup-count>

        <time-to-live-seconds>7200</time-to-live-seconds>

        <max-idle-seconds>600</max-idle-seconds>

        <eviction-policy>LRU</eviction-policy>

        <max-size policy="PER_NODE">0</max-size>

        <eviction-percentage>25</eviction-percentage>

        <min-eviction-check-millis>100</min-eviction-check-millis>

        <merge-policy>com.hazelcast.map.merge.PassThroughMergePolicy</merge-policy>

    </map>


    <services enable-defaults="true"/>

</hazelcast>

Here we declared a hazelcast map called ‘CustomerMap’. This map can be accessed in the application and can be used to store key value pairs. Some properties of hazelcast map are given below.


  • Backup-count  - Number of backups. If 1 is set as the backup-count for example, then all entries of the map will be copied to another JVM for fail-safety. 0 means no backup



  • Time-to-live-seconds - Maximum number of seconds for each entry to stay in the map. Entries that are older than time-to-live-seconds and not updated for time-to-live-seconds will get automatically evicted from the map
  • Max-idle-seconds - Maximum number of seconds for each entry to stay idle in the map.
  • Eviction-policy  -  Different eviction policies are available: NONE (no eviction), LRU (Least Recently Used), LFU (Least Frequently Used). NONE is the default.
  • Max-size -  Maximum size of the map. When max size is reached,map is evicted based on the policy defined. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0.
  • Eviction-percentage - When max. size is reached, specified percentage of the map will be evicted. Any integer between 0 and 100. If 25 is set for example, 25% of the entries will get evicted.
  • Merge-policy – There are different merge policies.
    • PassThroughMergePolicy - Entry will be added if there is no existing entry for the key.
    • HigherHitsMapMergePolicy - entry with the higher hits wins.
    • LatestUpdateMapMergePolicy - entry with the latest update wins.
  • Min-eviction-check-millis - Minimum time in milliseconds which should pass before checking if a partition of this map is evictable or not. Default value is 100 millis


Accessing Hazelcast Map in the application

At first we need to get reference to the hazelcast instance we declared in the spring context file. Here we use autowiring to get the hazelcast instance. After that hazelcast instance is used to create an ‘IMap’. Different types of maps are available like IMap, ConcrrentMap, MultiMap etc.

IMap is Concurrent, distributed, observable and queryable map. IMap does not allow nulls to be used as keys or values. Code snippet given below.

import org.springframework.beans.factory.annotation.Autowired;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;

public class HazelcastTest {

@Autowired
private HazelcastInstance hazelcastInstance;


public void addCustomers() throws Exception {

IMap<Integer, String> map = hazelcastInstance.getMap("CustomerMap");

map.put(1001, "Tom");
map.put(1002, "Jim");
map.put(1003, "Joe");
}

}
Above explaination will help to configure hazelcast with Spring and use hazelcast  IMap to
 store data.
Hazelcast Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Working With Spring Boot and Hazelcast (Distributed Cache)
  • Embracing Reactive Programming With Spring WebFlux
  • Building Real-Time Applications to Process Wikimedia Streams Using Kafka and Hazelcast
  • Spring Boot Annotations: Behind the Scenes and the Self-Invocation Problem

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: