springboot ehcache 基于外部文件的缓存

前言

前两天一直在研究缓存,网上很多帖子,关于springboot都是基于内存,缓存的数据,存活在程序的整个运行过程,无奈,研究了两天,才知道大致的思路,汗颜😓。

准备工作

  1. gradle中加入ehcache外部依赖
compile group: 'net.sf.ehcache', name: 'ehcache', version: '2.10.6'

如果使用maven,需要在mvrepository里面搜一下
在build.gradle文件里,plugins块中,添加Lombok

id "io.freefair.lombok" version "5.0.0-rc2"
  1. ehcache配置文件
<?xml version="1.0" encoding="UTF-8"?>

<ehcache>
    <!--
          磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
           path:指定在硬盘上存储对象的路径
    -->
    <diskStore path="D:\IdeaProjects\CacheTest\cache" />

    <!--
         defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
         maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
         eternal:代表对象是否永不过期
         overflowToDisk:当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
    -->
    <defaultCache
            maxElementsInMemory="100"
            eternal="true"
            overflowToDisk="true"
            timeToLiveSeconds="100"
    />

    <!--
        maxElementsInMemory设置成1,overflowToDisk设置成true,只要有一个缓存元素,就直接存到硬盘上去
        eternal设置成true,代表对象永久有效
        maxElementsOnDisk设置成0 表示硬盘中最大缓存对象数无限大
        diskPersistent设置成true表示缓存虚拟机重启期数据
     -->
    <cache
            name="local"
            maxElementsInMemory="1"
            timeToLiveSeconds="100"
            overflowToDisk="true"
            maxElementsOnDisk="0"
            diskPersistent="true"
            memoryStoreEvictionPolicy="LRU"
    />

    <cache
            name="databaseCache"
            maxElementsInMemory="1"
            timeToLiveSeconds="1000"
            overflowToDisk="true"
            maxElementsOnDisk="0"
            diskPersistent="true"
            memoryStoreEvictionPolicy="LRU"
    />

</ehcache>

cache标签可以有多个,对应不同的缓存区,实际执行的时候,对应不同的缓存文件
缓存文件

  1. application.properties中加入ehcache的配置文件路径
#enhance配置
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml

代码

  • 启动类 加上注解@EnableCaching开启缓存
package com.zr;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * @author 她家的猫
 */
@SpringBootApplication
@EnableCaching
public class CacheApplication{
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}
  • controller 设置请求路径
package com.zr.controller;

import com.zr.config.CacheUtils;
import com.zr.domain.User;
import com.zr.service.UserService;
import net.sf.ehcache.Cache;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 她家的猫
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/getById")
    public User getById(Integer id) {
        return userService.getById(id);
    }
    @RequestMapping("/print")
    public String print(String input) {
        return userService.print(input);
    }

    @RequestMapping("/delete")
    public String delete(Integer id) {
        userService.delete(id);
        return "删除成功";
    }

    /**查看缓存的内容*/
    @RequestMapping("/look")
    public Object look(){
        CacheUtils utils = CacheUtils.getInstance();
        Cache local = utils.get("local");
        return local.getAll(local.getKeys());
    }
}
  • service
package com.zr.service;

import com.zr.domain.User;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author 她家的猫
 */
@Service
@CacheConfig(cacheNames = "local")
/**cacheNames对应缓存文件里,cache标签后的name属性*/
public class UserService {

    @Cacheable(key="#id",condition = "#id>4")
    public User getById(Integer id) {
        System.out.println("没有缓存。。。");
        return new User(id, "getById", "123", 18);
    }

    @Cacheable(key="#input")
    public String print(String input) {
        System.out.println("没有缓存。。。");
        return input;
    }

    @CacheEvict(key="#id")
    public void delete(Integer id) {
        System.out.println("删除[" + id + "]缓存");
    }

}

其中,注解中的key的写法,是SPEL(需要自行搜索),如果不写key,缓存的键就是传入的变量的值

  • domain
package com.zr.domain;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

/**
 * @author 她家的猫
 */
@Data
@AllArgsConstructor
public class User implements Serializable {

    private Integer id;
    private String uname;
    private String pwd;
    private Integer age;

}
  • cacheUtils
package com.zr.config;

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

import java.net.URL;

/**
 * @author 她家的猫
 */
public class CacheUtils {

    private static final String PATH = "/ehcache.xml";

    private URL url;

    private final CacheManager manager;

    private static CacheUtils ehCache;

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

    public static CacheUtils getInstance() {
        if (ehCache== null) {
            ehCache= new CacheUtils(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);
    }
	/**cacheName对应缓存文件里,cache标签后的name属性*/
    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
        /*cache.removeAll();*/
    }
}

希望对你能有帮助

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值