Cache, I believe everyone is familiar with it. In the project, cache is definitely essential. There are many caching tools on the market, such as Redis, Guava Cache or EHcache.
I think everyone must be very familiar with these tools, so we won’t talk about them today. Let’s talk about how to implement local caching. Referring to the above tools, to achieve a better local cache, Brother Pingtou believes that we should start from the following three aspects.
1. Selection of storage collections
To implement local caching, the storage container must be a data structure in the form of key/value. In Java, it is our commonly used Map gather. There are HashMap, Hashtable, and ConcurrentHashMap in Map for us to choose from. If we do not consider data security issues under high concurrency, we can choose HashMap. If we consider data security issues under high concurrency, we can choose one of Hashtable and ConcurrentHashMap. Collection, but we prefer ConcurrentHashMap because the performance of ConcurrentHashMap is better than Hashtable.
2. Expired cache processing
Because the cache is stored directly in the memory, if we do not handle the expired cache, the memory will be occupied by a large number of invalid caches, which is not what we want Yes, so we need to clean these invalid caches. Expired cache processing can be implemented by referring to the Redis strategy. Redis adopts a regular deletion and lazy elimination strategy.
Periodic deletion strategy
The periodic deletion strategy is to detect expired caches at regular intervals and delete them. The advantage of this strategy is that it ensures that expired caches are deleted. There are also disadvantages. Expired caches may not be deleted in time. This is related to the timing frequency we set. Another disadvantage is that if there is a lot of cached data, each detection will also put a lot of pressure on the cup. .
Lazy elimination strategy
The lazy elimination strategy is to first determine whether the cache has expired when using the cache. If it expires, delete it and return empty. The advantage of this strategy is that it can only determine whether it is expired when searching, which has less impact on CUP. At the same time, this strategy has a fatal shortcoming. When a large number of caches are stored, these caches are not used and have expired, and they will become invalid caches. These invalid caches will occupy a large amount of your memory space, and eventually cause the server memory to overflow. .
We briefly took a look at the two expiration cache processing strategies of Redis. Each strategy has its own advantages and disadvantages. Therefore, during use, we can combine the two strategies, and the combined effect is still very ideal.
3. Cache elimination strategy
Cache elimination should be distinguished from expired cache processing. Cache elimination means when the number of our caches reaches the number of caches we specify. After all, our memory is not infinite. If we need to continue adding caches, we need to eliminate some caches in the existing caches according to a certain strategy to make room for the newly added caches. Let's learn about several commonly used cache elimination strategies.
First in, first out policy
The data that enters the cache first will be cleared first when the cache space is insufficient to free up new space to accept new data. The data. This strategy mainly compares the creation time of cached elements. In some scenarios that require relatively high data effectiveness, this type of strategy can be considered to give priority to ensuring that the latest data is available.
Least used strategy
Regardless of whether it is expired or not, based on the number of times the element has been used, clear elements that have been used less often to free up space. This strategy mainly compares the hitCount (number of hits) of elements. This type of strategy can be selected in scenarios where the validity of high-frequency data is ensured.
Least recently used strategy
Regardless of whether it is expired or not, based on the last used timestamp of the element, clear the element with the furthest used timestamp to free up space. This strategy mainly compares the time when the cache was last used by get. It is more applicable in hot data scenarios, and priority is given to ensuring the validity of hot data.
Random elimination strategy
Randomly eliminate a cache regardless of whether it expires. If there are no requirements for cached data, you can consider using this strategy.
Non-elimination strategy
When the cache reaches the specified value, no cache will be eliminated, but no new caches can be added. No more caches can be added until a cache is eliminated. .
The above are three points that need to be considered to implement local cache. After reading this, we should know how to implement a local cache. Let's implement a local cache together.
Implement local cache
In this Demo, we use ConcurrentHashMap as the storage collection, so that we can ensure the safety of the cache even in high concurrency situations. For expired cache processing, I only used the scheduled deletion strategy here, and did not use the scheduled deletion and lazy elimination strategy. You can try it yourself and use these two strategies for expired cache processing. In terms of cache eviction, I'm going with a least-use strategy here. Okay, now that we know the technical selection, let’s take a look at the code implementation.
Cache object class
public class Cache implements Comparable<Cache>{ // 键 private Object key; // 缓存值 private Object value; // 最后一次访问时间 private long accessTime; // 创建时间 private long writeTime; // 存活时间 private long expireTime; // 命中次数 private Integer hitCount; ...getter/setter()...
Add cache
/** * 添加缓存 * * @param key * @param value */ public void put(K key, V value,long expire) { checkNotNull(key); checkNotNull(value); // 当缓存存在时,更新缓存 if (concurrentHashMap.containsKey(key)){ Cache cache = concurrentHashMap.get(key); cache.setHitCount(cache.getHitCount()+1); cache.setWriteTime(System.currentTimeMillis()); cache.setAccessTime(System.currentTimeMillis()); cache.setExpireTime(expire); cache.setValue(value); return; } // 已经达到最大缓存 if (isFull()) { Object kickedKey = getKickedKey(); if (kickedKey !=null){ // 移除最少使用的缓存 concurrentHashMap.remove(kickedKey); }else { return; } } Cache cache = new Cache(); cache.setKey(key); cache.setValue(value); cache.setWriteTime(System.currentTimeMillis()); cache.setAccessTime(System.currentTimeMillis()); cache.setHitCount(1); cache.setExpireTime(expire); concurrentHashMap.put(key, cache); }
Get cache
/** * 获取缓存 * * @param key * @return */ public Object get(K key) { checkNotNull(key); if (concurrentHashMap.isEmpty()) return null; if (!concurrentHashMap.containsKey(key)) return null; Cache cache = concurrentHashMap.get(key); if (cache == null) return null; cache.setHitCount(cache.getHitCount()+1); cache.setAccessTime(System.currentTimeMillis()); return cache.getValue(); }
Get the least used cache
/** * 获取最少使用的缓存 * @return */ private Object getKickedKey() { Cache min = Collections.min(concurrentHashMap.values()); return min.getKey(); }
Expired cache detection method
/** * 处理过期缓存 */ class TimeoutTimerThread implements Runnable { public void run() { while (true) { try { TimeUnit.SECONDS.sleep(60); expireCache(); } catch (Exception e) { e.printStackTrace(); } } } /** * 创建多久后,缓存失效 * * @throws Exception */ private void expireCache() throws Exception { System.out.println("检测缓存是否过期缓存"); for (Object key : concurrentHashMap.keySet()) { Cache cache = concurrentHashMap.get(key); long timoutTime = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - cache.getWriteTime()); if (cache.getExpireTime() > timoutTime) { continue; } System.out.println(" 清除过期缓存 : " + key); //清除过期缓存 concurrentHashMap.remove(key); } } }
The above is the detailed content of To implement Java local cache, start from these points. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
