Java系列 - Ehcache实现

Ehcache缓存实现

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

Java系列 - Ehcache实现_第1张图片

<dependency>
    <groupId>org.apache.shirogroupId>
    <artifactId>shiro-spring-boot-web-starterartifactId>
    <version>1.10.0version>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-cacheartifactId>
dependency>


<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-coreartifactId>
    <version>2.13.4version>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-annotationsartifactId>
    <version>2.13.4version>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.13.4version>
dependency>
  1. application.yml中配置缓存配置文件地址
spring:

  cache:
    type: ehcache
    ehcache:
      config: classpath:/config/ehcache.xml
  1. 创建缓存配置文件: ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

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

    
    
    
    
    
    
    
    
    
    
    
    <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 [email protected]
 * @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());
    }
    
}

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

你可能感兴趣的:(java,mybatis,开发语言)