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);
    }
}
相关推荐
智购科技无人售货机厂家9 小时前
2026自动售货机制冷系统维护指南:从散热器清洁到压缩机换油的工程实践~YH
运维·redis·物联网·缓存·架构
2601_9621284114 小时前
SpringBoot篇(缓存层)
java·spring boot·缓存
2501_9378609414 小时前
Java多线程初阶(下)—— synchronized、volatile、wait/notify与经典并发工具
java·开发语言·jvm
mmsy102415 小时前
缓存知识点总结
java·spring·缓存
garmin Chen17 小时前
redis面试题
java·数据库·redis·缓存
二十雨辰18 小时前
[Java]-JVM面试题
java·开发语言·jvm
IT_Octopus18 小时前
G1 与 GC 日志入门课程(以本次离线菜单 Full GC 事故为教材)
java·jvm
疯狂打码的少年1 天前
【数据库技术】关系代数连接运算(等值连接/自然连接/外连接)
jvm·数据库·笔记·oracle
程序员夏洛1 天前
Redis 的 Red Lock 是什么?你了解吗?
数据库·redis·缓存
智购科技智能售货柜1 天前
2026自动售货机设备能耗计量系统:从功率监测到能效分析的工程实践~YH
数据库·人工智能·redis·缓存·架构·perl·symfony