How to set TTL on Hazelcast cache map with spring cacheble
Asked Answered
M

1

5

I am using Hazelcast cluster cache with spring boot. I am using the 4.2 version of hazelcast.

Caching is working fine but it doesn't evict the data from the cache map after TTL. Always keeping the same data. I tried a lot of ways of setting ttl but didn't get any success.

Here is my chance config class

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.spring.cache.HazelcastCacheManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {

  @Value("${hazelcast.cluster-name}")
  private String hzClusterName;

  @Value("${hazelcast.address}")
  private String hzAddress;

  @Bean
  HazelcastInstance hazelcastInstance() {
    return HazelcastClient.newHazelcastClient(clientConfig());
  }

  @Bean
  public ClientConfig clientConfig() {
    ClientConfig cfg = ClientConfig.load();
    cfg.setClusterName(hzClusterName);
    cfg.getNetworkConfig().addAddress(hzAddress);
    return cfg;
  }

  @Bean
  public CacheManager cacheManager() {
    return new HazelcastCacheManager(hazelcastInstance());
  }
}

The cache class where I am using cacheable

@Cacheable("items")
public String getInfo(String systemSkuRef) {
  logger.debug("Not using cache, fetch and put in cache");
  return "Item Info";
}

I tried by using hazelcast.yaml file in src/main/resources by setting

hazelcast:
  network:
      public-address: 
  cluster-name: dev
  map:
    items:
      time-to-live-seconds: 120
      max-idle-seconds: 60
      eviction:
        eviction-policy: LRU
        max-size-policy: PER_NODE
        size: 1000

is there any other way or how can I achieve this, Thanks for your help

Maturation answered 27/5, 2021 at 11:10 Comment(0)
F
7

There are two topologies in which you can use Hazelcast: Embedded and Client-Server. Your Java Spring configuration configures Hazelcast Client, however your hazelcast.yaml is dedicated for the Embedded mode.

Try to either use your hazelcast.yaml configuration in your Hazelcast server. Or configure your cache in the Hazelcast client, for example, like this:

@Bean
HazelcastInstance hazelcastInstance() {
    HazelcastInstance instance = HazelcastClient.newHazelcastClient(clientConfig());
    instance.getConfig().addMapConfig(new MapConfig("items").setTimeToLiveSeconds(120));
    return instance;
}
Freestone answered 28/5, 2021 at 12:47 Comment(1)
Thanks @Rafal It is working like charm. thank you so much for your helpMaturation

© 2022 - 2024 — McMap. All rights reserved.