JAVA 简单缓存实现-nacos

这篇博客介绍了Java中定义的一个缓存接口`Cache`,包括`put`、`get`、`get`带回调函数、`remove`和`clear`等方法。接着,给出了基于`HashMap`的简单缓存实现`SimpleCache`和基于`LinkedHashMap`的LRU缓存实现`LruCache`。最后,展示了一个自动过期缓存`AutoExpireCache`,它在`get`操作时会检查过期并移除过期条目。这些实现为Java缓存提供了基础功能和优化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义缓存接口:

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();
}

基于Java-Map的本地缓存实现:

public class SimpleCache<K, V> implements Cache<K, V> {
    
    private Map<K, V> cache;
    
    public SimpleCache(int size) {
        cache = new HashMap<>(size);
    }
    
    @Override
    public void put(K key, V val) {
        cache.put(key, val);
    }
    
    @Override
    public V get(K key) {
        return cache.get(key);
    }
    
    @Override
    public V get(K key, Callable<? extends V> call) throws Exception {
        if (cache.containsKey(key)) {
            return cache.get(key);
        } else {
            V v2 = call.call();
            cache.put(key, v2);
            return v2;
        }
    }
    
    @Override
    public V remove(K key) {
        return cache.remove(key);
    }
    
    @Override
    public void clear() {
        cache.clear();
    }
    
    @Override
    public int getSize() {
        return cache.size();
    }
}

基于LinkedHashMap的LruCache实现:

public class LruCache<K, V> implements Cache<K, V> {
    
    private final Cache<K, V> delegate;
    
    private Map<K, V> keyMap;
    
    private K eldestKey;
    
    public LruCache(Cache<K, V> delegate, int size) {
        this.delegate = delegate;
        setSize(size);
    }
    
    @Override
    public int getSize() {
        return delegate.getSize();
    }
    
    public void setSize(final int size) {
        keyMap = new LinkedHashMap<K, V>(size, .75F, true) {
            private static final long serialVersionUID = 4267176411845948333L;
            
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                boolean tooBig = size() > size;
                if (tooBig) {
                    eldestKey = eldest.getKey();
                }
                return tooBig;
            }
          
        };
    }
    
    @Override
    public void put(K key, V val) {
        delegate.put(key, val);
        cycleKeyList(key);
    }
    
    @Override
    public V get(K key) {
        keyMap.get(key);
        return delegate.get(key);
    }
    
    @Override
    public V get(K key, Callable<? extends V> call) throws Exception {
        return this.delegate.get(key, call);
    }
    
    @Override
    public V remove(K key) {
        return delegate.remove(key);
    }
    
    @Override
    public void clear() {
        delegate.clear();
        keyMap.clear();
    }
    
    private void cycleKeyList(K key) {
        keyMap.put(key, null);
        if (eldestKey != null) {
            delegate.remove(eldestKey);
            eldestKey = null;
        }
    }
    
}

自动过期缓存实现:

public class AutoExpireCache<K, V> implements Cache<K, V> {
    
    private long expireNanos;
    
    private Cache<K, V> delegate;
    
    private HashMap<K, CacheItemProperties> keyProp = new HashMap<>();
    
    public AutoExpireCache(Cache<K, V> delegate, long expireNanos) {
        this.expireNanos = expireNanos;
        this.delegate = delegate;
    }
    
    @Override
    public void put(K key, V val) {
        keyProp.put(key, cacheItemProperties());
        this.delegate.put(key, val);
    }
    
    @Override
    public V get(K key) {
        if (keyProp.get(key) != null && isExpire(keyProp.get(key))) {
            this.keyProp.remove(key);
            this.delegate.remove(key);
            return null;
        }
        return this.delegate.get(key);
    }

    @Override
    public V get(K key, Callable<? extends V> call) throws Exception {
        V cachedValue = this.get(key);
        if (null == cachedValue) {
            V v2 = call.call();
            this.put(key, v2);
            return v2;

        }
        return cachedValue;

    }
    
    @Override
    public V remove(K key) {
        keyProp.remove(key);
        return this.delegate.remove(key);
    }
    
    @Override
    public void clear() {
        keyProp.clear();
        this.delegate.clear();
    }
    
    @Override
    public int getSize() {
        return this.delegate.getSize();
    }
    
    private boolean isExpire(CacheItemProperties itemProperties) {
        if (itemProperties == null) {
            return true;
        }
        return expireNanos != -1 && (System.nanoTime() - itemProperties.getExpireNanos() > expireNanos);
    }
    
    private CacheItemProperties cacheItemProperties() {
        CacheItemProperties cacheItemProperties = new CacheItemProperties();
        cacheItemProperties.setExpireNanos(System.nanoTime());
        return cacheItemProperties;
    }
}

java缓存实现demo完整实例,很不错的资源,欢迎大家来下载学习。/** * 此函数接受一个对象列表,数目不定,opration:表是触发的事件 * eg:change;fnClear:表示初始化下拉框。var_args表示多个下拉框... */ function bindSelects(operation, initSelectObj, loadShow, var_args){ //每个argument对象都有一个 change事件 //change事件会触发:此argument之后的对象清空,紧跟此对象的后一对象发送ajax请求 var elementList = []; for (var i = 3; arguments[i]; i++) { elementList[i-3] = arguments[i]; } for (var i = 0; elementList[i]; i++) { (function(k) { elementList[k].bind(operation, function(){ selectType = elementList[k].attr("name"); //其后的对象进行某个操作 for (var j = k+1; elementList[j]; j++) { if (initSelectObj && initSelectObj.constructor===Function) { if(elementList[k].val() == "") { initSelectObj(elementList[j],elementList[j].data(SELECT_KEY)); LOAD_KEYS[j].hide(); } else{ initSelectObj(elementList[j],elementList[j].data(SELECT_KEY)); } } } //紧跟对象发送ajax if (elementList[k+1]) { if(elementList[k].val() != "") { //从页面缓存中取出 if(elementList[k+1].data(elementList[k].val())) { var data = elementList[k+1].data(elementList[k].val()); var key=LIST_KEYS[k]; var jsonKey = [key]; addContentToSelect(data,jsonKey,elementList[k+1]); } else { //从缓存中取出数据 if (fnAjax && fnAjax.constructor===Function) { loadShow(LOAD_KEYS[k+1]); fnAjax(elementList[k+1].data(SELECT_KEY),LIST_KEYS[k],LOAD_KEYS[k+1],elementList[k],selectType); } } } } }); })(i); } }
r-nacos 是一个用于与 Nacos 服务进行交互的 R 语言客户端库,主要面向使用 R 进行开发的微服务或云原生应用。它为开发者提供了便捷的方式来实现服务注册、服务发现以及配置管理等功能,从而使得 R 应用可以无缝集成到基于 Nacos 的微服务架构中。 ### 技术实现 r-nacos 的技术实现参考了其他语言(如 Java)中的 Nacos 客户端设计,并针对 R 语言的特点进行了适配和优化。其核心功能包括: - **服务注册**:r-nacos 允许 R 应用在启动时自动将自身注册到 Nacos Server 中,并提供自身的元数据信息,例如 IP 地址、端口等[^2]。 - **服务发现**:通过调用 r-nacos 提供的 API,R 应用可以动态地获取已注册的服务实例列表,并根据需要选择合适的服务实例进行调用[^1]。 - **健康检查**:r-nacos 支持客户端心跳机制,定期向 Nacos Server 发送心跳以表明服务实例处于可用状态,防止被剔除[^2]。 - **配置管理**:r-nacos 还支持从 Nacos Server 动态拉取配置信息,并能够在配置发生变更时实时更新本地缓存,确保应用始终使用最新的配置[^3]。 ### 使用指南 以下是一个简单的示例,展示如何使用 r-nacos 进行服务注册和服务发现: #### 服务注册 ```r library(rnacos) # 初始化 Nacos 客户端 client <- NacosClient$new(server_addr = "127.0.0.1:8848") # 注册服务实例 service_instance <- list( ip = "192.168.1.100", port = 8080, service_name = "example-service", metadata = list( health_check_url = "http://192.168.1.100:8080/health", homepage = "http://192.168.1.100:8080" ) ) # 调用注册方法 client$register_service(service_instance) ``` #### 服务发现 ```r # 获取服务实例列表 service_instances <- client$get_service_instances("example-service") # 输出服务实例信息 print(service_instances) ``` 上述代码展示了如何通过 r-nacos 将一个服务实例注册到 Nacos Server,并获取某个服务的所有实例列表。此外,r-nacos 还提供了对配置管理的支持,可以通过类似的方式获取和监听配置项的变化。 ### 相关库 除了 r-nacos 外,还有许多其他语言Nacos 客户端库,例如: - **Java**:Nacos 提供了官方的 Java 客户端,广泛用于 Spring Cloud Alibaba 生态中。 - **Python**:PyNacos 是一个社区驱动的 Python 客户端,支持服务注册、服务发现和配置管理。 - **Go**:GoNacos 是一个 Go 语言实现Nacos 客户端,适用于 Go 开发者构建微服务应用。 - **Node.js**:Nacos Node SDK 是一个 Node.js 实现Nacos 客户端,支持主流的 Node.js 框架。 这些客户端库的设计理念和功能基本一致,均围绕服务注册、服务发现和配置管理展开,但在具体实现上会根据语言特性进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值