spring cache (默认方式)


前置

什么是springcache:

通过注解就能实现缓存功能, 简化在业务中去操作缓存
Spring Cache只是提供了一层抽象, 底层可以切换不同的cache实现. 通过CacheManager接口来统一不同的缓存技术

会演示springcache的使用方式
项目地址

注意点

官网地址:
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#cache
默认方式是使用ConcurrentMap进行数据的保存, 下方有介绍

相关缓存文章

spring cache (默认方式)
spring cache (Redis方式)
spring cache (ehcache方式)


pom

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

配置

启动类上添加注解

@EnableCaching

示列代码

/**
 * @Cacheable: 参数释义
 * value相当于缓存空间的名称, 而key相当于是一个缓存值的名字
 * cacheManager和cacheResolver参数是互斥的, 指定这两个参数的操作会导致异常, 因为自定义cacheManager会被cacheResolver实现忽略
 *
 * key: 缓存的 key, 可以按 SpEL 表达式编写,为空时默认为方法的全参, 除非配置了 keyGenerator
 *      value(cacheNames): 缓存的名称, 可以多个
 * keyGenerator: key 的生成器. key 和 keyGenerator 二选一使用
 * cacheManager: 指定缓存管理器. 从哪个缓存管理器里面获取缓存
 * cacheResolver: 管理缓存管理器, CacheResolver 保持一个 cacheManager 的引用,并通过它来检索缓存
 * condition: 该参数采用SpEL计算为 true 或者 false. true: 缓存该方法 false: 不被缓存
 * unless: 与 condition 不同的是,unless表达式是在方法被调用后计算. true: 缓存该方法 false: 不被缓存
 * sync: 简单点讲, 避免瞬时流量涌入直接打入数据库. true: 可以有效的避免这种情况(缓存击穿)
 */
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@Cacheable(value = "selectById", key = "#id", sync = true)
public Object selectById(@PathVariable("id") Long id) {
    return sysUserService.selectById(id);
}

/**
 * @Cacheable: 使用多参数指定 key
 */
@RequestMapping(value = "/page", method = RequestMethod.GET)
@ResponseBody
@Cacheable(value = "selectPage", key = "#page + '-' + #size")
public Object selectPage(@RequestParam(value = "page", required = true) Integer page,
                         @RequestParam(value = "size", required = true) Integer size) {
    return sysUserService.selectPage(page, size);
}

/**
 * @CacheEvict: 补充参数释义, 其余参数可参考 @Cacheable
 *
 * allEntries: 是否删除缓存中的所有条目. 默认情况下, 只移除相关键下的值. 注意: 参数设置为 true 会忽略key
 * beforeInvocation: 是否应该在调用方法之前进行驱逐.
 *      true: 将导致不管方法结果如何(是否抛出异常)都将发生驱逐. 调用方法之前发生
 *      false(默认值): 意味着在成功调用方法后, 缓存清除操作将发生(即仅当调用没有抛出异常时)。
 *
 * 使用释义:
 *      新增数据, 查询时可自行加入缓存
 *      分页的情况, 会导致已缓存的分页数据结构异常, 清空分页数据, 从新加入缓存
 */
@RequestMapping(value = "/insert", method = RequestMethod.POST)
@ResponseBody
@CacheEvict(value = "selectPage", allEntries = true, beforeInvocation = true)
public Object insert(@Validated @RequestBody SysUserDTO.InsertSysUserDTO insertSysUserDTO) {
    return sysUserService.insert(insertSysUserDTO);
}

/**
 * @CachePut: 可参考 @Cacheable
 *      将返回结果更新至对应的缓存, 需要指定 key
 * @Caching:
 *      将多个注解进行组合使用, 支持: Cacheable, CachePut, CacheEvict
 *
 * 使用释义:
 * 该方法根据ID更新, 将返回结果更新至对应的缓存, 使用 @CachePut
 * 数据更新了, 但是分页的接口也使用了缓存, 但是分页的参数存在条数页数, 故将分页的缓存进行清空处理, 使用 @CacheEvict
 */
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ResponseBody
@Caching(
        put = @CachePut(value = "selectById", key = "#updateSysUserDTO.id"),
        evict = @CacheEvict(value = "selectPage", allEntries = true, beforeInvocation = true)
)
public Object update(@Validated @RequestBody SysUserDTO.UpdateSysUserDTO updateSysUserDTO) {
    return sysUserService.update(updateSysUserDTO);
}

/**
 * @CacheEvict:
 * 删除接口, 建议配置allEntries = true, 指定 key 可能无法指定清除复杂缓存, 如分页的缓存
 *
 * 使用释义:
 *      清空缓存, 这个地方可以使用组合注解: @Caching 根据ID清除指定的缓存(根据ID查询接口添加的缓存),
 * 在清除所有的分页缓存. (@Caching(evict={@CacheEvict(自行补充), @CacheEvict(自行补充)})
 *      删除对应的数据, 肯定要处理对应的缓存. 入参ID可通过指定 key 清除指定的缓存
 * 但是分页接口无法通过入参进行指定的缓存清除, 故干脆配置 allEntries = true 清除所有缓存
 */
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
@CacheEvict(value = {"selectById", "selectPage"}, allEntries = true, beforeInvocation = true)
public Object deleteById(@PathVariable("id") Long id) {
    return sysUserService.deleteById(id);
}

效果图

部分源码

关键类

关键类: org.springframework.cache.Cache
org.springframework.cache.interceptor.CacheInterceptor#invoke
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
实现类: org.springframework.cache.concurrent.ConcurrentMapCache

流程

在这里插入图片描述
在这里插入图片描述

代码描述 (此类无用, 只是备注源码的逻辑)

MyCacheAspectSupport.java 此类无用, 只是备注源码的逻辑:

package com.chaim.spring.cache.config;/*
 * Copyright 2002-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.*;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.expression.EvaluationContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.function.SingletonSupplier;
import org.springframework.util.function.SupplierUtils;

public abstract class MyCacheAspectSupport{
    private Object execute(final CacheOperationInvoker invoker, Method method, CacheOperationContexts contexts) {
        // 同步调用的特殊处理
        if (contexts.isSynchronized()) {
            CacheOperationContext context = contexts.get(CacheableOperation.class).iterator().next();
            if (isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) {
                Object key = generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT);
                Cache cache = context.getCaches().iterator().next();
                try {
                    return wrapCacheValue(method, cache.get(key, () -> unwrapReturnValue(invokeOperation(invoker))));
                }
                catch (Cache.ValueRetrievalException ex) {
                    // The invoker wraps any Throwable in a ThrowableWrapper instance so we
                    // can just make sure that one bubbles up the stack.
                    throw (CacheOperationInvoker.ThrowableWrapper) ex.getCause();
                }
            }
            else {
                // 不需要缓存,只调用底层方法
                return invokeOperation(invoker);
            }
        }


        // 判断@CacheEvict,是否有需要执行beforeInvocation,提前清除
        processCacheEvicts(contexts.get(CacheEvictOperation.class), true,
                CacheOperationExpressionEvaluator.NO_RESULT);

        // 检查是否有匹配条件的缓存项
        // 根据 CacheableOperation 去查缓存, 在 MultiValueMap 中查找缓存(第3步)
        // 然后在根据生成的 key 到全局常量 Collection<? extends Cache> caches 中查找缓存(第5步)
        Cache.ValueWrapper cacheHit = findCachedItem(contexts.get(CacheableOperation.class));

        // 如果缓存未命中, 则新增到cachePutRequests,后续执行原始方法后会写入缓存
        List<CachePutRequest> cachePutRequests = new LinkedList<>();
        if (cacheHit == null) {
            collectPutRequests(contexts.get(CacheableOperation.class),
                    CacheOperationExpressionEvaluator.NO_RESULT, cachePutRequests);
        }

        Object cacheValue;
        Object returnValue;
        // 缓存存在使用缓存, 不存在调用目标方法
        if (cacheHit != null && !hasCachePut(contexts)) {
            // 缓存命中的情况, 使用缓存值作为结果
            cacheValue = cacheHit.get();
            returnValue = wrapCacheValue(method, cacheValue);
        }
        else {
            // 如果没有缓存命中,就调用目标方法
            returnValue = invokeOperation(invoker);
            cacheValue = unwrapReturnValue(returnValue);
        }

        // 如果有@CachePut注解, 则新增到cachePutRequests, 因为@CachePut修饰的方法需要每次都更新缓存值
        collectPutRequests(contexts.get(CachePutOperation.class), cacheValue, cachePutRequests);

        // 更新缓存值, 将结果添加到全局常量 Collection<? extends Cache> caches 中(第5步)
        for (CachePutRequest cachePutRequest : cachePutRequests) {
            cachePutRequest.apply(cacheValue);
        }

        // 执行被@CacheEvict修饰的,需要缓存剔除的值
        processCacheEvicts(contexts.get(CacheEvictOperation.class), false, cacheValue);

        return returnValue;
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值