SpringBoot + EhCache 实现缓存

在开发中我们经常会使用到缓存技术,有时候并不是很需要像redis这样外部内存服务器。那么ehCache是一个不错的选择,它是一个Java进程内的缓存框架,只需要加入所需依赖进行配置就可以使用。我们通过springboot快速入门ehCache。

准备

  1. 引入依赖

    net.sf.ehcache
    ehcache


  1. ehCache配置文件ehcache.xml


    
    

    

    
    
    
    

    
    
    
    
    
    
    

    

    

    


  1. springboot 配置 application.properties
spring.cache.ehcache.config=/ehcache.xml    # ehCache.xml 所在路径  
  1. 缓存注解
@SpringBootApplication
@EnableCaching // 使能springboot缓存机制
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

简单实例

public void contextLoads() {

        // 构建缓存管理器
        CacheManager cacheManager = CacheManager.create();
        // 查看所有缓存实例,这些在ehcache.xml 配置的缓存
        String[] cacheNames = cacheManager.getCacheNames();

        // 获取缓存对象
        Cache weibo = cacheManager.getCache("weibo");

        // 存入缓存
        Element element  = new Element("key","value");
        weibo.put(element );
        // 从缓存中取出
        Element abc = weibo.get("key");


    }

实现缓存中模糊搜索

  1. 在配置文件中开启搜索功能
  
    

    
  1. 搜索缓存
@Test
    public void contextLoads() {
        // 构建缓存管理器
        CacheManager cacheManager = CacheManager.create();
        // 查看所有缓存实例,这些在ehcache.xml 配置的缓存
        String[] cacheNames = cacheManager.getCacheNames();
        // 获取缓存对象
        Cache weibo = cacheManager.getCache("weibo");
        // 存入缓存
        Element element  = new Element("key","value");
        weibo.put(element );
        weibo.put(new Element("key1","value1") );
        weibo.put(new Element("key2","value1") );
        weibo.put(new Element("key3","value1") );
        weibo.put(new Element("key4","value1") );
        // 从缓存中取出
        Element abc = weibo.get("key");

        Attribute key = weibo.getSearchAttribute("key");

        Query query = weibo.createQuery();
        ILike criteria = new ILike(key.getAttributeName(),"*key*");
        query.addCriteria(criteria );
        query.includeAttribute(key);
        Results execute = query.execute();

    }
 

                            
                        
                    
                    
                    

你可能感兴趣的:(SpringBoot + EhCache 实现缓存)