springboot本地缓存ehcache存取数据,cacheable缓存

直接上代码,原来自己看

1、在resource下新建ehcache.xml



    

    
    
    
    
    
    
    
    
    
    

    
    
    

2、新建EhcacheUtil.java通用方法类

package com.goldpac.ocs.business.merchantservice.config;
import java.net.URL;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhcacheUtil {
    private static final String path = "/ehcache.xml";

    private URL url;

    private CacheManager manager;

    private static EhcacheUtil ehCache;

    private EhcacheUtil(String path) {
    url = getClass().getResource(path);
    manager = CacheManager.create(url);
    }

    public static EhcacheUtil getInstance() {
        if (ehCache== null) {
        ehCache= new EhcacheUtil(path);
        }
        return ehCache;
}

    public void put(String cacheName, String key, Object value) {
        Cache cache = manager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);
    return element == null ? null : element.getObjectValue();
    }

    public Cache get(String cacheName) {
    return manager.getCache(cacheName);
}

    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
    }
}

3、导入jar包

       
            net.sf.ehcache
            ehcache-core
            2.4.3
            compile
        

4、service中调用

//获取缓存数据institutionNo为ehcache.xml中配置的name,no为获取缓存的数据key(我的no为变量)

Object institutionNo = EhcacheUtil.getInstance().get("institutionNo", no);

//添加缓存数据institutionNo为ehcache.xml中配置的name,no为缓存的数据的key,no2为缓存的value(我的no为变量)

EhcacheUtil.getInstance().put("institutionNo", no, no2);


另附一篇cacheable缓存,我的理解是,没有就执行方法并缓存结果,有就直接返回缓存,,

https://blog.csdn.net/zhuyu19911016520/article/details/81946202

 

你可能感兴趣的:(缓存)