Java系列 - Ehcache实现

Ehcache缓存实现

本文目的:本地缓存Ehcache实现

在这里插入图片描述

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-web-starter</artifactId>
    <version>1.10.0</version>
</dependency>
<!-- 开启 cache 缓存-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<!-- jackson -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.13.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.13.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.4</version>
</dependency>
  1. application.yml中配置缓存配置文件地址
spring:

  cache:
    type: ehcache
    ehcache:
      config: classpath:/config/ehcache.xml
  1. 创建缓存配置文件: 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"
         updateCheck="false">

    <diskStore path="D:\ehcache"/>

    <!--默认缓存策略 -->
    <!-- external:是否永久存在,设置为true则不会被清除,此时与timeout冲突,通常设置为false-->
    <!-- diskPersistent:是否启用磁盘持久化-->
    <!-- maxElementsInMemory:最大缓存数量-->
    <!-- overflowToDisk:超过最大缓存数量是否持久化到磁盘-->
    <!-- timeToIdleSeconds:最大不活动间隔,设置过长缓存容易溢出,设置过短无效果,可用于记录时效性数据,例如验证码-->
    <!-- timeToLiveSeconds:最大存活时间-->
    <!-- memoryStoreEvictionPolicy:缓存清除策略-->
    <!-- maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大 -->
    <!-- diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。-->
    <!-- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。
 可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。-->
    <defaultCache
            eternal="false"
            diskPersistent="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskSpoolBufferSizeMB="50"
            timeToIdleSeconds="60"
            timeToLiveSeconds="60"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="smsCode"
            eternal="false"
            diskPersistent="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            timeToIdleSeconds="10"
            timeToLiveSeconds="10"
            memoryStoreEvictionPolicy="LRU"/>

    <cache name="cacheOne"
           eternal="false"
           diskPersistent="false"
           maxElementsInMemory="1000"
           overflowToDisk="false"
           timeToIdleSeconds="60"
           timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LRU"/>

    <cache name="cacheTwo"
           eternal="false"
           diskPersistent="false"
           maxElementsInMemory="1000"
           overflowToDisk="false"
           timeToIdleSeconds="60"
           timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LRU"/>
</ehcache>

  1. 封装工具类。其中涉及到一个json转换方法,使用的jackson,所以在上面导入了该坐标
package com.mock.water.config.cache;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.jcache.config.JCacheConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * @Author ifredomvip@gmail.com
 * @Date 2023/4/1 13:39
 */
@Slf4j
@Configuration
public class EhCacheConfig extends JCacheConfigurerSupport {

    /**
     * 自定义缓存数据 key 生成策略
     * target: 类
     * method: 方法
     * params: 参数
     *
     * @return KeyGenerator
     * 注意: 该方法只是声明了key的生成策略,还未被使用,需在@Cacheable注解中指定keyGenerator
     * 如: @Cacheable(value = "key", keyGenerator = "keyGenerator")
     */
    @Override
    @Primary
    @Bean
    public KeyGenerator keyGenerator() {

        ObjectMapper mapper = new ObjectMapper();

        //new了一个KeyGenerator对象,采用lambda表达式写法
        //类名+方法名+参数列表的类型+参数值,然后再做md5转16进制作为key
        //使用冒号(:)进行分割,可以很多显示出层级关系
        return (target, method, params) -> {
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.append(target.getClass().getName());
            strBuilder.append(":");
            strBuilder.append(method.getName());
            for (Object obj : params) {
                if (obj != null) {
                    strBuilder.append(":");
                    strBuilder.append(obj.getClass().getName());
                    strBuilder.append(":");
                    try {
                        // java对象转换为json字符换
                        strBuilder.append(mapper.writeValueAsString(obj));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
            }
            //log.info("ehcache key str: " + strBuilder.toString());
            String md5DigestAsHex = DigestUtils.md5DigestAsHex(strBuilder.toString().getBytes(StandardCharsets.UTF_8));
            log.info("ehcache key md5DigestAsHex: " + md5DigestAsHex);
            return md5DigestAsHex;
        };
    }

}
  1. 通过注解使用
package com.mock.water.modules.system.user.service;
import com.mock.water.modules.system.user.entity.UserEntity;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.cache.annotation.CacheConfig;

public interface UserService extends IService<UserEntity> {

    UserEntity findAllCache(String cacheKey);
    
    UserEntity findCache(String cacheKey);

    UserEntity updateCache(String cacheKey);
    
    boolean deleteCache(String cacheKey);
}
package com.mock.water.modules.system.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mock.water.modules.system.user.entity.UserEntity;
import com.mock.water.modules.system.user.mapper.UserMapper;
import com.mock.water.modules.system.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@CacheConfig(cacheNames = {"cacheOne"})
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {


    /**
     * 查询所有
     * 缓存是存的是什么呢? 
     * 将被标注方法的返回结果进行缓存
     * cacheNames: 指令缓存名称.必须在ehCache.xml配置文件中创建
     * cacheNames + keyGenerator
     */
    @Cacheable(cacheNames = "cacheTwo", keyGenerator = "keyGenerator")
    @Override
    public List<UserEntity> findAllCache(String cacheKey) {
        System.out.println(cacheKey);

        List<UserEntity> allUser = baseMapper.selectList(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, "admin"));

        return allUser;
    }
    
    /**
     * 查询
     * 缓存是存的是什么呢? 
     * 将被标注方法的返回结果进行缓存
     * cacheKey 的长度为3
     * condition表示的是条件(为true才缓存)
     */
    @Cacheable(key = "#cacheKey", condition = "#cacheKey.length==3")
    @Override
    public UserEntity findCache(String cacheKey) {
        System.out.println(cacheKey);

        UserEntity user = baseMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, "admin"));

        System.out.println("useCache查询");
        return user;
    }
    /**
     * 更新
     * 将被标注方法的返回结果进行缓存
     * condition表示的是条件(为true才缓存)
     */
    @CachePut( key = "#cacheKey", condition = "#cacheKey=='token'")
    @Override
    public UserEntity updateCache(String cacheKey) {

        Optional<UserEntity> optional = Optional.ofNullable(baseMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, "admin")));

        if(!optional.isPresent()){
            return null;
        }

        UserEntity user = optional.get();
        user.setNickname(cacheKey);
        baseMapper.updateById(user);

        return user;
    }

    /**
     * 更加id,删除
     *
     * @CacheEvict Spring会在调用该方法之前清除缓存中的指定元素
     * allEntries : 为true表示清除value空间名里的所有的数据,默认为false
     * beforeInvocation 缓存的清除是在方法前执行还是方法后执行,默认是为false,方法执行后删除
     * beforeInvocation = false : 方法执行后删除,如果出现异常缓存就不会清除
     * beforeInvocation = true : 方法执行前删除,无论方法是否出现异常,缓存都清除
     */

    @CacheEvict(key = "#cacheKey", beforeInvocation = true)
    @Override
    public boolean deleteCache(String cacheKey) {
        log.info("deleteById查询数据库");
        try {
            baseMapper.deleteById(cacheKey);
            log.info("删除成功");
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
  1. controller调用测试。

测试结果:缓存成功。

第一次查询会进入数据库查询。第二次查询,不会再从数据库查询。

package com.mock.water.modules.system.user.controller;

import com.mock.water.modules.system.user.entity.UserEntity;
import com.mock.water.modules.system.user.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("")
@Slf4j
public class UserController {
    
    @Autowired
    private UserService userService;

    @GetMapping("/getUserinfo/{id}")
    public void getUserinfo(@PathVariable("id") String id) {
        log.info("findById请求时间:{}", LocalDateTime.now());
        
        UserEntity user = userService.findCache(token);
        
        log.info("findById返回结果:{}", user);
        log.info("findById返回时间:{}", LocalDateTime.now());
        
    }

    @GetMapping("/updateCache/{id}")
    public void updateCache(@PathVariable("id") String id) {
        log.info("updateById请求时间:{}", LocalDateTime.now());

        UserEntity user = userService.updateCache(token);

        log.info("updateById返回结果:{}", user);
        log.info("updateById返回时间:{}", LocalDateTime.now());
    }
    
}

------ 如果文章对你有用,感谢右上角 >>>点赞 | 收藏 <<<

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值