一、本地缓存设计
1、Nacos的缓存结构设计为例,通用缓存为例,支持不同模式的缓存,
支持更复杂功能,可以直接使用Guava和Caffine直接使用.
①、Cache缓存接口.
package com.alibaba.nacos.common.cache;
import java.util.concurrent.Callable;
/**
* Cache method collection definition.
* @author zzq
* @date 2021/7/30
*/
public interface Cache<K, V> {
/**
* Cache a pair of key value. If the key value already exists, the value will be overwritten.
* @param key cache key
* @param val cache value
*/
void put(K key, V val);
/**
* Take the corresponding value from the cache according to the cache key.
* @param key cache key
* @return cache value
*/
V get(K key);
/**
* Get the value in the cache according to the primary key, and put it into the cache after processing by the function.
* @param key cache key
* @param call a function, the return value of the function will be updated to the cache
* @return cache value
* @throws Exception callable function interface throw exception
*/
V get(K key, Callable<? extends V> call) throws Exception;
/**
* Take the corresponding value from the cache according to the cache key, and remove this record from the cache.
* @param key cache key
* @return cache value
*/
V remove(K key);
/**
* Clear the entire cache.
*/
void clear();
/**
* Returns the number of key-value pairs in the cache.
* @return number of key-value pairs
*/
int getSize();
}
②、CacheItemProperties【通用缓存项配置】
package com.alibaba.nacos.common.cache.builder;
/**
* Cache item's own attributes.
* @author zzq
* @date 2021/7/30
*/
public class CacheItemProperties {
private long expireNanos;
public long getExpireNanos() {
return expireNanos;
}
public void setExpireNanos(long expireNanos) {
this.expireNanos = expireNanos;
}
}
2、缓存实现
①、SimpleCache,不带任何功能.
package com.alibaba.nacos.common.cache.impl;
import com.alibaba.nacos.common.cache.Cache;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* Simple implementation of {@code Cache}.
* @author zzq
* @date 2021/7/30
*/
public class SimpleCache<K, V> implements Cache<K, V> {
private Map<K, V> cache;

文章介绍了Nacos中缓存的设计,包括Cache接口及其通用缓存项配置,展示了SimpleCache、AutoExpireCache(实现过期清理)、SynchronizedCache(线程安全)和LruCache(LRU缓存)四种不同的实现方式,以及如何通过CacheBuilder构建不同特性的缓存。
最低0.47元/天 解锁文章
2218

被折叠的 条评论
为什么被折叠?



