Skip to content

Instantly share code, notes, and snippets.

@IMRFeng
Last active October 29, 2020 04:27
Show Gist options
  • Save IMRFeng/92420ade40532663369ebd693dec7a8b to your computer and use it in GitHub Desktop.
Save IMRFeng/92420ade40532663369ebd693dec7a8b to your computer and use it in GitHub Desktop.
How to use hazelcast as the implemention of Spring Boot Caching

What Hazelcast is?

Hazelcast is a distributed computing and simplified leading open source In-Memory Data Grid(IMDG).

Why would we use it in the micro-services as a caching solution?

  1. Spring Boot has a general support for Hazelcast.

  2. Hazelcast is distributed, fast, easy to cluster and easy to test.

  3. Pretty straightforward to integrate with Spring Boot.

How to use it?

  1. Add spring.cache.type=hazelcast into application.properties.

  2. You can define a com.hazelcast.config.Config bean, otherwise, Spring Boot tries to find the Hazelcast configuration from the default locations, that is hazelcast.xml in the working directory or at the root of the classpath (e.g. src/main/resources) or you could also specify the hazelcast.xml configuration file to use via configuration: spring.hazelcast.config=classpath:config/my-hazelcast.xml.

  3. Enable the cache using @EnableCaching annotation to your root main method of Spring Boot.

    Note: the hazelcast.xml looks like:

    <?xml version="1.0" encoding="UTF-8"?>
    <hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config http://www.hazelcast.com/schema/config/hazelcast-config-3.7.xsd"
    		xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    
    	<group>
    		<name>boot-micro-services</name>
    		<password>micro-services-pwd</password>
    	</group>
    
    	<map name="userInfo">
    		<time-to-live-seconds>315360000</time-to-live-seconds> <!-- Maximum time in seconds for each entry to stay in the map -->
    		<max-idle-seconds>14400</max-idle-seconds> <!-- Maximum time in seconds for each entry to stay idle in the map. 4 hours here -->
    		<eviction-policy>LFU</eviction-policy> <!-- The entries least frequently used will be evicted -->
    		<max-size>20000</max-size> <!-- Maximum size of the userInfo map -->
    		<eviction-percentage>25</eviction-percentage> <!-- When max-size is reached, the specified percentage of the map will be evicted. -->
    	</map>
    
    	<network>
    		<join>
    			<multicast enabled="false"/>
    			<tcp-ip enabled="true">
    				<member>127.0.0.1</member>
    				<!--<member>127.0.0.1-21</member>-->
    			</tcp-ip>
    		</join>
    	</network>
    
    </hazelcast>

Basic usage of Spring Cache Annotationssd

  1. Spring cache provides a set of Java annotations, but the frequently used annotations are: Cacheable, CachePut and CacheEvict.

    @Cacheable triggers cache population, put @Cacheable on the method which you want to cache.
    @Cacheable(value = "userInfo", key = "#token")
    public UserInfo getUserInfo(String token) throws NoUserInfoException {
    	return getUserInfoFromDB(token);
    }

    Here getUserInfo() method is marked with @Cacheable, whenever getUserInfo() is called it will check the userInfo, if the data is already existing there it will return that one, otherwise it will executes the getUserInfoFromDB() and returns data.

  2. @CachePut updates the cache without interfering with the method execution.

    @CachePut(value = "userInfo", key = "#token")
    public UserInfo getUserInfoFromDB(String token) throws NoUserInfoException {
    	Response response = restTemplate.getForObject(urlTemplate, Response.class, token);
    	return response.getBody();
    }
  3. @CacheEvict triggers cache eviction, will be used to delete the data from existing cache.

    @CacheEvict(value = "userInfo", key = "#token")
    public void invalidateCacheEntry(String token) {
    }

    Whenever a invalidateCacheEntry() is called the userInfo cache will be deleted.

References

  1. https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html
  2. http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-hazelcast.html
  3. http://docs.hazelcast.org/docs/3.5/manual/html/map-eviction.html
  4. http://docs.hazelcast.org/docs/3.5/manual/html/networkconfiguration.html
@pikeno221
Copy link

it helped a lot... finally i know how to create custom ttl for each entity that I insert in cache. thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment