国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Google的guava緩存學(xué)習(xí)使用

這篇具有很好參考價(jià)值的文章主要介紹了Google的guava緩存學(xué)習(xí)使用。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

導(dǎo)入依賴

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>31.1-jre</version>
</dependency>

使用1

項(xiàng)目中使用到了緩存,定義一個(gè)切面,攔截類或方法上存在@SysDataCache注解請(qǐng)求,對(duì)于這些方法的返回值進(jìn)行緩存。項(xiàng)目中主要還是使用在緩存常量,一些不易改變的值

定義注解

@Documented
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SysDataCache {

}

定義切面和初始化緩存容器并使用緩存

@Aspect   //定義一個(gè)切面
@Configuration
public class SysDataCacheAspect {
    private static Logger logger = LogManager.getLogger(SysDataCacheAspect.class);
    private static final  Map<String,Boolean> cacheFileNames = new ConcurrentHashMap<String, Boolean>();

    private static LoadingCache<String,Object> cache = null;
    static {
        // CacheLoader 初始化
        CacheLoader<String, Object> cacheLoader = new CacheLoader<String, Object>() {
            @Override
            // load方法的作用是在通過(guò)get方法從LoadingCache獲取不到值時(shí)去加載該值并放入緩存。
            public Object load(String key) throws Exception {
                return null;
            }
        };
        cache = CacheBuilder.newBuilder()
                // 設(shè)置容量大小
                .maximumSize(80000)
                //默認(rèn)一天后過(guò)期
                .expireAfterWrite(10, TimeUnit.DAYS)
                .removalListener(new RemovalListener<String, Object>() {
                    @Override
                    public void onRemoval(RemovalNotification<String, Object> notification) {
                        if(notification.getValue()!=null && notification.getValue() instanceof CacheFile) {
                            CacheFile cacheFile = (CacheFile)notification.getValue();
                            removeCacheFile(cacheFile.fileName);
                        }
                        
                    }
                })
                // 加載器配置
                .build(cacheLoader);
    }
    
    private String normalizedArgsStr(Object[] args){
        if(args==null || args.length==0) {
            return "";
        }
        Object[] normalizedArgs = new Object[args.length];
        if(args!=null) {
            for(int i=0;i<args.length;i++) {
                Object arg = args[i];
                
                if(arg instanceof AccessTokenUser) {
                    AccessTokenUser user = (AccessTokenUser)arg;
                    normalizedArgs[i]= user.getUserId();
                }else {
                    normalizedArgs[i]=arg;
                }
            }
        }
        return JsonConverter.toJsonStr(normalizedArgs);
    }
    
    @Around("execution(* (@com.xysd.bizbase.annotation.SysDataCache *).*(..)) || execution(@com.xysd.bizbase.annotation.SysDataCache * *(..))")
    public Object process(ProceedingJoinPoint point) throws Throwable {
        String className = point.getSignature().getDeclaringTypeName();
        String methodName = point.getSignature().getName();
        Object[] args = point.getArgs();
        String key = className+"_$_"+methodName+"_$_"+(normalizedArgsStr(args));
        Object cached = cache.getIfPresent(key);
        
        if(methodName.endsWith("_dontCache")){
            return point.proceed(args);
        }
        if(cached!=null) {
            if(cached instanceof CacheFile) {
                CacheFile cachedFile = (CacheFile)cached;
                Object cachedData =  readCachedData(cachedFile);
                if(cachedData==null) {
                    //讀取緩存失敗
                    return point.proceed(args);
                }else {
                    return cachedData;
                }
            }else {
                return cached;
            }
            
        }else {
            cached = point.proceed(args);
            if(cached instanceof ApiResultDTO){
                if(((ApiResultDTO<?>) cached).getData() == null) return cached;
            }
            if(cached!=null) {
                try {
                    CacheFile cachedFile = cacheToDiskIfNecessary(cached);
                    if(cachedFile!=null) {
                        cache.put(key, cachedFile);
                    }else {
                        cache.put(key, cached);
                    }
                    
                }catch(Exception e) {
                    logger.error("緩存失敗,失敗信息{}",e.getMessage());
                    e.printStackTrace();
                }
                
            }
            return cached;
        }
    }
    private Object readCachedData(CacheFile cachedFile) {
        String fileName = cachedFile.getFileName();
        String absolutePath = getAbsoluteCacheFilePath(fileName);
        File f = new File(absolutePath);
        InputStream in = null;
        ObjectInputStream oin = null;
        try {
            in = new FileInputStream(f);
            oin = new ObjectInputStream(in);
            Object cachedData = oin.readObject();
            return cachedData;
        }catch(Exception e) {
            logger.error("讀取緩存序列化文件失敗,失敗信息:{}",e.getMessage());
            e.printStackTrace();
            return null;
        }
        finally {
            Utils.clean(in,oin);
        }
        
    }
    /**
     * 當(dāng)value序列化后占用字節(jié)大于50K時(shí)寫入磁盤進(jìn)行緩存
     * @param value
     * @return
     */
    private CacheFile cacheToDiskIfNecessary(Object value) {
        int cachThreadshold = 50*1024;
        ByteArrayOutputStream bos = null ; 
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(value);
            oos.flush();
            byte[] byteArray = bos.toByteArray();
            if(byteArray!=null && byteArray.length>cachThreadshold) {
                return buildCacheFile(byteArray);
            }else {
                return null;
            }
        }catch(Exception e) {
            throw new RuntimeException(e);
        }finally {
            Utils.clean(bos,oos);
        }
    }
    
    private CacheFile buildCacheFile(byte[] byteArray) {
        String fileName = "syscachefile_"+Utils.getUUID("");
        String absolutePath = getAbsoluteCacheFilePath(fileName);
        File f = new File(absolutePath);
        OutputStream out = null;
        try {
            if(!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            out = new FileOutputStream(f);
            out.write(byteArray);
            out.flush();
            cacheFileNames.put(fileName, true);
            return new CacheFile(fileName);
        }catch(Exception e) {
            
            throw new RuntimeException(e);
        }finally {
            Utils.clean(out);
        }
        
    }
    
    private static String getAbsoluteCacheFilePath(String fileName) {
        String sysCacheBaseDir = Utils.getTmpDirRoot()+"/sysDataCache";
        return sysCacheBaseDir+"/"+fileName;
    }
    
    public static void removeCacheFile(String fileName) {
        if(StringUtils.isNoneBlank(fileName)) {
            cacheFileNames.remove(fileName);
            String absolutePath = getAbsoluteCacheFilePath(fileName);
            File f = new File(absolutePath);
            try {
                if(f.exists() && f.isFile()) {
                    f.delete();
                }
            }catch(Exception e) {
                //刪除失敗不做任何處理
                e.printStackTrace();
            }
        }
    }
    /**
     * 清空緩存
     */
    public static final void clearCache() {
        for(String fileName:cacheFileNames.keySet()) {
            removeCacheFile(fileName);
        }
        cacheFileNames.clear();
        cache.invalidateAll();
    }
    
    public static class CacheFile implements Serializable {
        private static final long serialVersionUID = -6926387004863371705L;
        private String fileName;
        public CacheFile(String fileName) {
            super();
            this.fileName = fileName;
        }
        public String getFileName() {
            return fileName;
        }
    }
    
}

項(xiàng)目中緩存使用

@Service
@Transactional
@SuppressWarnings("unchecked")
public class SysDatasServiceImpl implements _ISysDatasService {
    private final static ConstantItem dataKey_dict_politicalStatus = new ConstantItem("politicalStatus", "政治身份");

	@Override
    @SysDataCache
    @Transactional(readOnly = true)
    public Map<String, String> getSysDataKeysInfo(AccessTokenUser user) {
		result.put((String) dataKey_dict_politicalStatus.getId(), dataKey_dict_politicalStatus.getName());
	}
	@Override
    @SysDataCache
    @Transactional(readOnly = true)
    public Map<String, Object> getSysDatasByDataKeys(AccessTokenUser user, Map<String, Object> dataKeyAndParams) {
    	if (dataKey_dict_politicalStatus.getId().equals(entry.getKey())) {//政治身份
                Map<String, Object> dictParams = (Map<String, Object>) entry.getValue();
                data.put(entry.getKey(), getDictValue(entry.getKey(), dictParams));
                continue;
        }
    }
    //從字典中獲取數(shù)據(jù)
    private List<SimpTreeNode> getDictValue(String dictCodes, Map<String, Object> params) {
        if("all".equals(dictCodes)){
            List<SysDataSimpleDTO> rootDicts = systemGatewayService.findAllRootDicts(1);
            dictCodes = Optional.ofNullable(rootDicts).orElse(new ArrayList<>()).stream().map(r->r.getId().replace("-","")).collect(Collectors.joining(","));
        }
        else if (params != null && params.get("dictCodes") != null) {
            dictCodes = (String) params.get("dictCodes");
            params.remove("dictCodes");
        }
        List<SimpTreeNode> codeList = systemGatewayService.findDictSimTreeNodeByDictCodes(dictCodes, params);
        return codeList;
    }
}

使用2

作為性能緩存工具,這里是作為統(tǒng)計(jì)sql查詢的耗時(shí),當(dāng)然這是基于內(nèi)存的緩存,如果需要保留下來(lái)??梢圆迦氲綌?shù)據(jù)庫(kù)中文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-823864.html

記錄sql執(zhí)行過(guò)程實(shí)體模型

public class MonitorTask {
    public static final String STATUS_RUUNING = "running";
    public static final String STATUS_END = "end";
    public static final String STATUS_FAILED = "failed";
    private Date beginTime;//開(kāi)始時(shí)間
    private String content;//sql
    private String taskId;//任務(wù)id uuid
    private Date endTime;//結(jié)束時(shí)間
    private String status = STATUS_RUUNING;//任務(wù)執(zhí)行狀態(tài)

    public MonitorTask(String content, String taskId) {
        super();
        this.content = content;
        this.taskId = taskId;
        //指定任務(wù)開(kāi)始時(shí)間
        this.beginTime = new Date();
    }

    public Date getBeginTime() {
        return beginTime;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public void setBeginTime(Date beginTime) {
        this.beginTime = beginTime;
    }

    public void finished(boolean success) {
        //指定任務(wù)結(jié)束時(shí)間
        this.endTime = new Date();
        if (success) {
            status = STATUS_END;
        } else {
            status = STATUS_FAILED;
        }

    }

    public String getStatus() {
        return status;
    }

    public boolean isFailed() {
        return STATUS_FAILED.equals(this.status);
    }

    public boolean isSuccess() {
        return STATUS_END.equals(this.status);
    }

    public long getCost() {
        if (this.endTime == null) {
            return 0;
        } else if (this.endTime.getTime() > this.beginTime.getTime()) {
            return this.endTime.getTime() - this.beginTime.getTime();
        } else {
            return 0;
        }

    }

}

任務(wù)性能統(tǒng)計(jì)實(shí)體模型

public class TaskStat {
	private String content;
	//執(zhí)行總數(shù)
	private volatile int totalCount;

	//總耗時(shí)
	private volatile long totalCost;
	//最近一次耗時(shí)
	private volatile long lastCost;

	public int getTotalCount() {
		return totalCount;
	}

	public long getTotalCost() {
		return totalCost;
	}

	public long getLastCost() {
		return lastCost;
	}

	public void finish(MonitorTask task) {
		this.totalCount++;
		this.totalCost += task.getCost();
		this.lastCost = task.getCost();

	}


	public TaskStat(String content) {
		super();
		this.content = content;
	}

	//平均時(shí)耗
	public double getAvgCost() {
		if (this.totalCount == 0) {
			return 0;
		} else {
			return this.totalCost / this.totalCount;
		}
	}

	public String getContent() {
		return content;
	}

}

任務(wù)統(tǒng)計(jì)邏輯執(zhí)行過(guò)程

//執(zhí)行統(tǒng)計(jì)邏輯
public class PerformanceStat {

    //緩存任務(wù)執(zhí)行的開(kāi)始時(shí)間,結(jié)束時(shí)間,成功與否,任務(wù)狀態(tài)等等
    private static LoadingCache<String, MonitorTask> runningTasks = null;

    static {
        // CacheLoader 初始化
        CacheLoader<String, MonitorTask> cacheLoader1 = new CacheLoader<String, MonitorTask>() {
            @Override
            // load方法的作用是在通過(guò)get方法從LoadingCache獲取不到值時(shí)去加載該值并放入緩存。
            public MonitorTask load(String key) throws Exception {
                return null;
            }
        };
        runningTasks = CacheBuilder.newBuilder()
                // 設(shè)置容量大小
                .maximumSize(50000)

                //默認(rèn)一天后過(guò)期
                //.expireAfterWrite(60*24, TimeUnit.MINUTES)
                // 加載器配置
                .build(cacheLoader1);
    }

    //緩存任務(wù)總耗時(shí),平均耗時(shí),總執(zhí)行次數(shù)
    private static LoadingCache<String, TaskStat> taskStats = null;

    static {
        // CacheLoader 初始化
        CacheLoader<String, TaskStat> cacheLoader = new CacheLoader<String, TaskStat>() {
            @Override
            // load方法的作用是在通過(guò)get方法從LoadingCache獲取不到值時(shí)去加載該值并放入緩存。
            public TaskStat load(String key) throws Exception {
                return null;
            }
        };
        taskStats = CacheBuilder.newBuilder()
                // 設(shè)置容量大小
                .maximumSize(200000)

                //默認(rèn)一天后過(guò)期
                //.expireAfterWrite(60*24, TimeUnit.MINUTES)
                // 加載器配置
                .build(cacheLoader);
    }

    /**
     * 開(kāi)始監(jiān)控任務(wù)
     *
     * @param content 監(jiān)控任務(wù)內(nèi)容
     * @return
     */
    public static MonitorTask beginTask(String content) {
        MonitorTask task = new MonitorTask(content, UUID.randomUUID().toString());
        runningTasks.put(task.getTaskId(), task);
        TaskStat stat = taskStats.getIfPresent(task.getContent());
        if (stat == null) {
            stat = new TaskStat(content);
            taskStats.put(task.getContent(), stat);
        }
        return task;
    }

    /**
     * 任務(wù)完成
     *
     * @param task
     * @param success
     */
    public static void finishTask(MonitorTask task, boolean success) {
        if (task == null) {
            return;
        }
        TaskStat stat = taskStats.getIfPresent(task.getContent());
        task.finished(success);
        runningTasks.invalidate(task.getTaskId());
        if (stat != null) {
            stat.finish(task);
        }

    }

    //清空緩存
    public static void clear() {
        runningTasks.invalidateAll();
        taskStats.invalidateAll();
    }

    //排序
    public static List<TaskStat> sort(String sortType) {
        List<TaskStat> stats = new ArrayList<TaskStat>(taskStats.asMap().values());
        if ("1".equals(sortType)) {
            //按照總耗時(shí)倒序排序
            Collections.sort(stats, new Comparator<TaskStat>() {

                @Override
                public int compare(TaskStat o1, TaskStat o2) {

                    return Long.valueOf(o2.getTotalCost()).compareTo(Long.valueOf(o1.getTotalCost()));
                }
            });
        }
        if ("2".equals(sortType)) {
            //按照平均耗時(shí)倒序排序
            Collections.sort(stats, new Comparator<TaskStat>() {

                @Override
                public int compare(TaskStat o1, TaskStat o2) {

                    return Double.valueOf(o2.getAvgCost()).compareTo(Double.valueOf(o1.getAvgCost()));
                }
            });
        }
        return stats;
    }
}

定義攔截sql執(zhí)行的InvocationHandler

public class QueryProxy implements InvocationHandler {
    private Object target;
    private MonitorTask task;
    //指定攔截下面這些方法
    private static final List<String> jdbcMethods = Arrays.asList("getSingleResult", "getResultList", "executeUpdate", "getResultList", "uniqueResult", "getSingleResult", "list");


    public QueryProxy(String content, Object target) {
        super();
        this.target = target;
        task = PerformanceStat.beginTask(content.toLowerCase());

    }

    private boolean isJdbcMethod(Method method) {
        String n = method.getName();

        if (jdbcMethods.contains(n)) {
            return true;
        } else {
            return false;
        }
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            Object result = method.invoke(target, args);
            if (this.isJdbcMethod(method)) {
                PerformanceStat.finishTask(task, true);
            }
            return result;
        } catch (RuntimeException e) {
            if (this.isJdbcMethod(method)) {
                PerformanceStat.finishTask(task, true);
            }
            throw e;
        }
    }

    @SuppressWarnings("unchecked")
    public static final <T> T newProxyQuery(Class<T> queryClass, String content, Object target) {
        QueryProxy proxyHandler = new QueryProxy(content, target);
        return (T) Proxy.newProxyInstance(QueryProxy.class.getClassLoader(), new Class[]{queryClass}, proxyHandler);
    }

}

查詢接口

@RequestMapping(value="/holiday", method=RequestMethod.GET)
    public String queryHoliday(HttpServletRequest request){
        return myService.getHolidayByYear();
    }
public String getHolidayByYear(){
        Date year = CalendarUtils.getCurrentYearBeginDate();
        year = CalendarUtils.offsetYears(year,-1);
        List<DateRec> holidays = commonRepositoryHibernate.getHolidayByYear(year);
        if (CollectionUtils.isEmpty(holidays)) return null;
        return JsonConverter.toJsonStr(holidays);
    }
public List<DateRec> getHolidayByYear(Date year){
        String hql = "select d from " + DateRec.class.getName() + " d where d.valid = 1 and dateTime >= :dateTime ";
        List<DateRec> holidays = this.createHQLQueryByMapParams(DateRec.class, hql, Utils.buildMap("dateTime", year)).list();
        if (holidays == null) holidays = new ArrayList<>();
        return holidays;
    }

攔截sql

private boolean isMonitorPerformance() {
	//這里可以通過(guò)配置文件配置
     return true;
}
/**
     * 創(chuàng)建query
     * 通過(guò)params設(shè)置query查詢參數(shù)
     * @param <T>
     * @param hql
     * @param params
     */
    protected <T> Query<T> createHQLQueryByMapParams(Class<T> resultType,String hql,Map<String,Object> params){
        Query<T> query = JpaQueryBuilder.createHQLQueryByMapParams(getSession(), resultType, hql, params);
        if(isMonitorPerformance()) {
            return QueryProxy.newProxyQuery(Query.class, hql,query);
        }
        return query;
}

查看sql性能監(jiān)控

@ApiImplicitParam(name="sort", value="排序類型")
    @RequestMapping(value="/stat", method=RequestMethod.GET)
    public List<TaskStat> stat(@RequestParam String sort,
                                             HttpServletRequest request){
        return PerformanceStat.sort(sort);
    }
//排序
    public static List<TaskStat> sort(String sortType) {
        List<TaskStat> stats = new ArrayList<TaskStat>(taskStats.asMap().values());
        if ("1".equals(sortType)) {
            //按照總耗時(shí)倒序排序
            Collections.sort(stats, new Comparator<TaskStat>() {

                @Override
                public int compare(TaskStat o1, TaskStat o2) {

                    return Long.valueOf(o2.getTotalCost()).compareTo(Long.valueOf(o1.getTotalCost()));
                }
            });
        }
        if ("2".equals(sortType)) {
            //按照平均耗時(shí)倒序排序
            Collections.sort(stats, new Comparator<TaskStat>() {

                @Override
                public int compare(TaskStat o1, TaskStat o2) {

                    return Double.valueOf(o2.getAvgCost()).compareTo(Double.valueOf(o1.getAvgCost()));
                }
            });
        }
}

到了這里,關(guān)于Google的guava緩存學(xué)習(xí)使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Google 開(kāi)源庫(kù)Guava詳解

    Guava 是一組來(lái)自Google的核心Java庫(kù),包括新的集合類型(如多映射和多集)、不可變集合、圖庫(kù)和并發(fā)、I/O、哈希、原語(yǔ)、字符串等實(shí)用程序!它廣泛用于Google中的大多數(shù)Java項(xiàng)目,也被許多其他公司廣泛使用。 Guava?開(kāi)發(fā)要求?: JRE風(fēng)格需要JDK 1.8或更高版本。 如果您需要支持

    2024年02月09日
    瀏覽(31)
  • 【Guava】Guava: Google Core Libraries for Java 好用工具類

    Guava是Google的一組核心Java庫(kù),其中包括 新的集合類型 (如multimap和multiset) 、 不可變集合 、 圖庫(kù) ,以及用于 并發(fā)、I/O、哈希、緩存、基元、字符串 等的實(shí)用程序!它 被廣泛用于谷歌內(nèi)的大多數(shù)Java項(xiàng)目,并被許多人廣泛使用。 Guava是一種基于開(kāi)源的Java庫(kù) ,Google Guava源于

    2024年02月11日
    瀏覽(21)
  • 【譯】Google Guava 的 Table 接口介紹

    【譯】Google Guava 的 Table 接口介紹

    原文:https://www.baeldung.com/guava-table 在本教程中,我們將展示如何使用 Google Guava 的 Table 接口及其多個(gè)實(shí)現(xiàn)。 Guava 的 Table 是一種集合,表示包含行、列和相關(guān)單元格值的表結(jié)構(gòu),行和列充當(dāng)有序的鍵對(duì)。 讓我們看看如何使用 Table 類。 2.1. Maven依賴 首先,在 pom.xml 中添加 Goo

    2024年02月06日
    瀏覽(25)
  • 推薦Java開(kāi)發(fā)常用的工具類庫(kù)google guava

    Guava Guava是一個(gè)Google開(kāi)源的Java核心庫(kù),它提供了許多實(shí)用的工具和輔助類,使Java開(kāi)發(fā)更加簡(jiǎn)潔、高效、可靠。目前和 hutool 一起,是業(yè)界常用的工具類庫(kù)。 shigen 也比較喜歡使用,在這里列舉一下常用的工具類庫(kù)和使用的案例。 參考: 整理一波Guava的使用技巧 - 掘金 Guava中這

    2024年02月09日
    瀏覽(23)
  • Google 開(kāi)源庫(kù)Guava詳解(集合工具類)—Maps、Multisets、Multimaps

    Maps有許多很酷的實(shí)用程序,值得單獨(dú)解釋。 Maps.uniqueIndex(Iterable,F(xiàn)unction)解決了一個(gè)常見(jiàn)的情況,即有一堆對(duì)象,每個(gè)對(duì)象都有一些唯一的屬性,并希望能夠根據(jù)該屬性查找這些對(duì)象。 假設(shè)我們有一堆字符串,我們知道它們有唯一的長(zhǎng)度,我們希望能夠查找具有特定長(zhǎng)度

    2024年02月03日
    瀏覽(27)
  • 【Guava筆記01】Guava Cache本地緩存的常用操作方法

    這篇文章,主要介紹Guava Cache本地緩存的常用操作方法。 目錄 一、Guava Cache本地緩存 1.1、引入guava依賴 1.2、CacheBuilder類 1.3、Guava-Cache使用案例

    2024年01月23日
    瀏覽(25)
  • 【java緩存、redis緩存、guava緩存】java中實(shí)現(xiàn)緩存的幾種方式

    【java緩存、redis緩存、guava緩存】java中實(shí)現(xiàn)緩存的幾種方式

    這種方式可以簡(jiǎn)單實(shí)現(xiàn)本地緩存,但是實(shí)際開(kāi)發(fā)中不推薦使用,下面我們來(lái)實(shí)現(xiàn)一下這種方式。 首先創(chuàng)建一個(gè)管理緩存的類 這個(gè)類中有一個(gè)靜態(tài)代碼塊,靜態(tài)代碼塊會(huì)在類加載時(shí)就執(zhí)行,我們可以在這里完成對(duì)緩存的初始化,決定緩存內(nèi)一開(kāi)始就有哪些數(shù)據(jù) 另外我們還可以

    2024年02月16日
    瀏覽(15)
  • Guava:Cache強(qiáng)大的本地緩存框架

    Guava:Cache強(qiáng)大的本地緩存框架

    Guava Cache是一款非常優(yōu)秀的本地緩存框架。 Guava Cache 的數(shù)據(jù)結(jié)構(gòu)跟 JDK1.7 的 ConcurrentHashMap 類似,提供了基于時(shí)間、容量、引用三種回收策略,以及自動(dòng)加載、訪問(wèn)統(tǒng)計(jì)等功能。 基本的配置 例子中,緩存最大容量設(shè)置為 100 ( 基于容量進(jìn)行回收 ),配置了 失效策略 和 刷新策

    2024年02月02日
    瀏覽(21)
  • 【Redis(8)】Spring Boot整合Redis和Guava,解決緩存穿透、緩存擊穿、緩存雪崩等緩存問(wèn)題

    在緩存技術(shù)的挑戰(zhàn)及設(shè)計(jì)方案我們介紹了使用緩存技術(shù)可能會(huì)遇到的一些問(wèn)題,那么如何解決這些問(wèn)題呢? 在構(gòu)建緩存系統(tǒng)時(shí),Spring Boot和Redis的結(jié)合提供了強(qiáng)大的支持,而Guava的 LoadingCache 則為緩存管理帶來(lái)了便捷的解決方案。下面我將介紹如何通過(guò)整合Spring Boot、Redis和Gu

    2024年04月22日
    瀏覽(23)
  • 【開(kāi)源與項(xiàng)目實(shí)戰(zhàn):開(kāi)源實(shí)戰(zhàn)】82 | 開(kāi)源實(shí)戰(zhàn)三(中):剖析Google Guava中用到的幾種設(shè)計(jì)模式

    【開(kāi)源與項(xiàng)目實(shí)戰(zhàn):開(kāi)源實(shí)戰(zhàn)】82 | 開(kāi)源實(shí)戰(zhàn)三(中):剖析Google Guava中用到的幾種設(shè)計(jì)模式

    上一節(jié)課,我們通過(guò) Google Guava 這樣一個(gè)優(yōu)秀的開(kāi)源類庫(kù),講解了如何在業(yè)務(wù)開(kāi)發(fā)中,發(fā)現(xiàn)跟業(yè)務(wù)無(wú)關(guān)、可以復(fù)用的通用功能模塊,并將它們從業(yè)務(wù)代碼中抽離出來(lái),設(shè)計(jì)開(kāi)發(fā)成獨(dú)立的類庫(kù)、框架或功能組件。 今天,我們?cè)賮?lái)學(xué)習(xí)一下,Google Guava 中用到的幾種經(jīng)典設(shè)計(jì)模式:

    2024年02月11日
    瀏覽(38)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包