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);
    }
}
相关推荐
库森学长5 小时前
面试官:发生OOM后,JVM还能运行吗?
jvm·后端·面试
描绘一抹色6 小时前
JVM基础01(从入门到八股-黑马篇)
jvm
夜斗小神社14 小时前
【黑马点评】(二)缓存
缓存
Hello.Reader21 小时前
Redis 延迟监控深度指南
数据库·redis·缓存
Hello.Reader1 天前
Redis 延迟排查与优化全攻略
数据库·redis·缓存
微风粼粼1 天前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
掘金-我是哪吒1 天前
分布式微服务系统架构第158集:JavaPlus技术文档平台日更-JVM基础知识
jvm·分布式·微服务·架构·系统架构
abigalexy1 天前
深入JVM底层-内存分配算法
jvm
在肯德基吃麻辣烫2 天前
《Redis》缓存与分布式锁
redis·分布式·缓存
先睡2 天前
Redis的缓存击穿和缓存雪崩
redis·spring·缓存