springboot hutool内存缓存


import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.http.HttpUtil;

/**
 * 
 */
public class IdCacheUtils {

    private static  TimedCache<String, String> cache = null;

    //默认缓存时长 单位s
    private static final Long DEFAULT_TIMEOUT = 5*60 * 60 * 60 * 1000L;// 60 * 1000L=1秒

    /**
     * 缓存
     */
    public static String getVal(String id){
        //初始化缓存
        if(null==cache){
            cache = CacheUtil.newTimedCache(DEFAULT_TIMEOUT);
            //启动定时任务,每100秒秒检查一次过期
            cache.schedulePrune(100000);
        }
        String res = cache.get(id);
        if(StrUtil.isNotBlank(res )){
            return res ;
        }
        String id = "123123";
        String val = "缓存值XXXXXX";//接口请求获得
        cache.put(id,val );
        return val;
    }
}

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Spring Boot和Caffeine实现内存缓存的步骤: 1.添加依赖关系 在pom.xml文件中添加以下依赖关系: ```xml <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.9.0</version> </dependency> ``` 2.创建缓存配置类 创建一个缓存配置类,用于配置缓存管理器和缓存类型。在这个类中,我们使用Caffeine作为缓存提供程序,并设置缓存的最大大小和过期时间。 ```java @Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager cacheManager() { CaffeineCacheManager cacheManager = new CaffeineCacheManager(); cacheManager.setCaffeine(caffeineCacheBuilder()); return cacheManager; } Caffeine<Object, Object> caffeineCacheBuilder() { return Caffeine.newBuilder() .maximumSize(100) .expireAfterAccess(5, TimeUnit.MINUTES) .weakKeys() .recordStats(); } } ``` 3.在需要缓存的方法上添加@Cacheable注释 在需要缓存的方法上添加@Cacheable注释,指定缓存的名称和键。当方法被调用时,如果缓存中已经存在相应的键,则直接返回缓存中的值,否则执行方法并将结果存储在缓存中。 ```java @Service public class MyService { @Cacheable(value = "myCache", key = "#id") public String getData(String id) { // 从数据库或其他数据源获取数据 return "data"; } } ``` 4.启动应用程序 在启动应用程序时,@EnableCaching注释将启用缓存支持,并使用我们在CacheConfig类中定义的缓存管理器。 ```java @SpringBootApplication @EnableCaching public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值