jvm一级缓存

1、利用JVM缓存。脱离redis。

2、导包,springboot自带此包。如没有可以导:com.google.guava:guava:20.0的包。

3、直接上代码:

java 复制代码
package com.leo.cache;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


/**
 * @author Leo
 */
@Component
public class JvmLruOneCacheComponent {

    Cache<String, String> allCache;

    @PostConstruct
    public void initCache() {
        allCache = CacheBuilder.newBuilder()
                .weakValues()
                最大容量
                .maximumSize(10L)
                //多少分钟后没有访问的数据会被清除
                .expireAfterAccess(30L, TimeUnit.MINUTES)
                // 设置并发级别为cpu核心数
                .concurrencyLevel(Runtime.getRuntime().availableProcessors() * 2)
                .build();
    }

    public Map<String, String> getCache() {
        return allCache.asMap();
    }


    @SneakyThrows
    public List<StockCrawlingResponseDto> getStockCrawlingList() {
        String key = "xxxxxxx";
        //先获取缓存。没有缓存就从后面的方法获取数据并存入缓存
        String jsonStr = allCache.get(key, () -> JSONObject.toJSONString(xxxxService.getData()));
        return JSONObject.parseArray(jsonStr, xxxdto.class);
    }

    public String getCacheByKey(String key) {
        return allCache.getIfPresent(key);
    }

    public void setCacheByKey(String key, String value) {
        allCache.put(key, value);
    }

    public void deleteAllCache() {
        allCache.invalidateAll();
    }

    public void deleteCache(String key) {
        allCache.invalidate(key);
    }
}
相关推荐
源分享3 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
JAVA9653 天前
JAVA面试-JVM篇 03-JVM运行时数据区哪些是线程私有的哪些是共享的
java·jvm·面试
ofoxcoding3 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
NeilYuen4 天前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss
taocarts_bidfans4 天前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
退休倒计时4 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
炘爚4 天前
Linux——Redis
数据库·redis·缓存
伶俜664 天前
鸿蒙原生应用实战(十八)ArkUI 记账本:SQLite 账单 + 图表统计 + 分类管理
jvm·sqlite·harmonyos
小挪号底迪滴4 天前
Redis 和 MySQL 数据不一致怎么办?缓存更新策略实战
redis·mysql·缓存