EhCache快速上手+简单应用

EhCache快速上手+简单应用

关于EhCache的特性、介绍就不多说了,CSDN里搜一搜EhCache会有很多介绍,本篇文章只记录下EhCache快速上手+简单应用。

1.导入EhCache的依赖

在springboot项目的pom.xml中,加入依赖

		<dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.6</version>
        </dependency>
2.添加ehcache.xml

在resource中新建ehcache的配置文件ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <!-- 磁盘缓存位置 -->
    <diskStore path="D:\shenji\practice\ehcacheData"/>

    <!-- 默认缓存 -->
    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!-- helloworld缓存 -->
    <cache name="HelloWorldCache"
           maxElementsInMemory="1"
           eternal="true"
           timeToIdleSeconds="5"
           timeToLiveSeconds="5"
           overflowToDisk="true"
           maxElementsOnDisk="0"
           diskPersistent="true"
           memoryStoreEvictionPolicy="LRU"/>

    <!-- StudentInfo缓存 -->
    <cache name="studentInfoCache"
           maxElementsInMemory="10000"
           eternal="true"
           timeToIdleSeconds="5"
           timeToLiveSeconds="5"
           overflowToDisk="true"
           maxElementsOnDisk="0"
           diskPersistent="true"
           memoryStoreEvictionPolicy="LRU"/>
    
</ehcache>

关于xml中各个属性的意思,可以参考

3.测试类

以下的例子是我从别的文章里复制的,虽然有点视觉疲劳,但是很好上手

package com.hm.country.test;

import com.hm.country.entity.Person;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhcacheTest {
    public static void main(String[] args) {
        // 1. 创建缓存管理器
        CacheManager cacheManager = CacheManager.create("D:\\shenji\\practice\\webapp\\src\\main\\resources\\ehcache.xml");
        // 2. 获取缓存对象
        Cache cache = cacheManager.getCache("HelloWorldCache");
        // 3. 创建元素
        Element element = new Element("key1", "value1");

        // 4. 将元素添加到缓存
        cache.put(element);

        // 5. 获取缓存
        Element value = cache.get("key1");
        //[ key = key1, value=value1, version=1, hitCount=1, CreationTime = 1601279306565, LastAccessTime = 1601279306587 ]
        System.out.println(value);
        //value1
        System.out.println(value.getObjectValue());

        // 6. 删除元素
        cache.remove("key1");

        Person p1 = new Person("小明",18,"杭州");
        Element pelement = new Element("xm", p1);
        cache.put(pelement);
        Element pelement2 = cache.get("xm");
        System.out.println(pelement2.getObjectValue());

        System.out.println(cache.getSize());

        // 7. 刷新缓存
        cache.flush();

        // 8. 关闭缓存管理器,释放内存
        cacheManager.shutdown();
    }

}

4.简单应用

在实际的使用中,一般都是经常需要访问的信息,或者访问数据库太繁琐的数据需要放到缓存中,可以提高效率。
数据库中我新建了一个学生表,然后创建了一个类,来模拟实际中查询学生信息。
在这里插入图片描述

4.1创建一个util类专门处理缓存
package com.hm.country.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhcacheUtil {
    private static String xmlLocation = "D:\\shenji\\practice\\webapp\\src\\main\\resources\\ehcache.xml";

    //通过缓存名称获取缓存
    public static Cache getCacheByName(String cachaName){
        CacheManager manager = CacheManager.create(xmlLocation);
        return manager.getCache( cachaName );
    }
    //判断某缓存中是否有某值
    public static boolean isInCache(String cacheName,Object key){
        CacheManager manager = CacheManager.create(xmlLocation);
        Cache cache = manager.getCache( cacheName );
        boolean returnFlag = true;
        if(cache == null){
            returnFlag =  false;
        }
        if(cache.get(key) == null){
            returnFlag =  false;
        }
        return returnFlag;
    }

    //将数据放入缓存中
    public static void putToCache(String cacheName,Element element){
        Cache cache = EhcacheUtil.getCacheByName( cacheName );
        cache.put( element );
    }

    //从缓存中拿数据
    public static Object getFromCache(String cacheName,Object key){
        CacheManager manager = CacheManager.create(xmlLocation);
        Cache cache = manager.getCache( cacheName );
        Object data;
        if(cache == null){
            data =  null;
        }
        if(cache.get(key) == null){
            data =  null;
        }
        Element element = cache.get( key );
        data = element.getObjectValue();
        return data;
    }


}

4.2业务逻辑编写
package com.hm.country.service.serviceImpl;

import com.hm.country.mapper.StudentMapper;
import com.hm.country.service.StudentService;
import com.hm.country.util.EhcacheUtil;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService{
    private static String studentInfoCache = "studentInfoCache";
    
    @Autowired
    StudentMapper studentMapper;
    @Override
    public String getStuInfoByNumber(String number) {
        String stuInfo = "";
        //首先去缓存里看看有没有
        boolean isInCache = EhcacheUtil.isInCache( studentInfoCache,number );
        //如果缓存里有,就从缓存里取
        if(isInCache){
            System.out.println("isInCache为true,缓存中有"+number+"的信息");
            stuInfo = String.valueOf(EhcacheUtil.getFromCache( studentInfoCache,number ));
            System.out.println("从缓存中取到的"+number+"的信息为:"+stuInfo);
        }else{
            //缓存里没有,就从数据库里取,并且把信息放到缓存里
            System.out.println("isInCache为false,缓存中没有"+number+"的信息");
            Map map = studentMapper.getStuInfoByNumber(number);
            stuInfo = "学号为"+number+"的学生,姓名是"+map.get("name")+
                    ",性别"+map.get("gender")+",地址在"+map.get( "address" );
            System.out.println("从数据库中查询到"+number+"的信息为:"+stuInfo);
            Element element = new Element(number,stuInfo);
            System.out.println("将"+number+"的信息放入缓存中");
            EhcacheUtil.putToCache( studentInfoCache,element );
        }
        return stuInfo;
    }
}


4.2测试结果

我创建了个接口访问上方的方法,浏览器先后两次访问http://localhost:8989/getStuInfoByNumber?number=20203602
日志如下:

isInCache为false,缓存中没有20203602的信息
从数据库中查询到20203602的信息为:学号为20203602的学生,姓名是河马,性别女,地址在池塘
将20203602的信息放入缓存中

isInCache为true,缓存中有20203602的信息
从缓存中取到的20203602的信息为学号为:20203602的学生,姓名是河马,性别女,地址在池塘

说明这个方法写得没有问题
在实际中的使用,也是先去查缓存中有没有,如果有就直接从缓存中取;没有的话就查库,并放到缓存里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值