【问题标题】:How to set TTL on Hazelcast cache map with spring cacheble如何使用spring cacheble在Hazelcast缓存地图上设置TTL
【发布时间】:2021-05-27 11:10:23
【问题描述】:

我正在使用带有 Spring Boot 的 Hazelcast 集群缓存。我正在使用 4.2 版本的 hazelcast。

缓存工作正常,但它不会在 TTL 之后从缓存映射中逐出数据。始终保持相同的数据。我尝试了很多设置ttl的方法,但都没有成功。

这是我的机会配置类

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());
  }
}

我使用可缓存的缓存类

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

我尝试通过设置在 src/main/resources 中使用 hazelcast.yaml 文件

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

有没有其他方法或者我怎样才能做到这一点,谢谢你的帮助

【问题讨论】:

    标签: java spring-boot hazelcast spring-cache


    【解决方案1】:

    您可以在两种拓扑中使用 Hazelcast:嵌入式和客户端-服务器。您的 Java Spring 配置配置了 Hazelcast 客户端,但您的 hazelcast.yaml 专用于嵌入式模式。

    尝试在您的 Hazelcast 服务器中使用您的 hazelcast.yaml 配置。或者在 Hazelcast 客户端中配置你的缓存,例如,像这样:

    @Bean
    HazelcastInstance hazelcastInstance() {
        HazelcastInstance instance = HazelcastClient.newHazelcastClient(clientConfig());
        instance.getConfig().addMapConfig(new MapConfig("items").setTimeToLiveSeconds(120));
        return instance;
    }
    

    【讨论】:

    • 谢谢@Rafal 它就像魅力一样工作。非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 2012-08-19
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多