欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解如何使用SpringBoot的緩存@Cacheable

 更新時(shí)間:2023年06月27日 11:28:40   作者:小石讀史  
這篇文章主要為大家介紹了如何使用SpringBoot的緩存@Cacheable詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

緩存介紹

Spring 從 3.1 開始就引入了對(duì) Cache 的支持。定義了 org.springframework.cache.Cache 和 org.springframework.cache.CacheManager 接口來統(tǒng)一不同的緩存技術(shù)。并支持使用 JCache(JSR-107)注解簡化我們的開發(fā)。

其使用方法和原理都類似于 Spring 對(duì)事務(wù)管理的支持。Spring Cache 是作用在方法上的,其核心思想是,當(dāng)我們在調(diào)用一個(gè)緩存方法時(shí)會(huì)把該方法參數(shù)和返回結(jié)果作為一個(gè)鍵值對(duì)存在緩存中。

Cache 和 CacheManager 接口說明

Cache 接口包含緩存的各種操作集合,你操作緩存就是通過這個(gè)接口來操作的。

Cache 接口下 Spring 提供了各種 xxxCache 的實(shí)現(xiàn),比如:RedisCache、EhCache、ConcurrentMapCache

CacheManager 定義了創(chuàng)建、配置、獲取、管理和控制多個(gè)唯一命名的 Cache。這些 Cache 存在于 CacheManager 的上下文中。

小結(jié):

每次調(diào)用需要緩存功能的方法時(shí),Spring 會(huì)檢查指定參數(shù)的指定目標(biāo)方法是否已經(jīng)被調(diào)用過,如果有就直接從緩存中獲取方法調(diào)用后的結(jié)果,如果沒有就調(diào)用方法并緩存結(jié)果后返回給用戶。下次調(diào)用直接從緩存中獲取。

二、@Cacheable 注解使用詳細(xì)介紹

@Cacheable 這個(gè)注解,用它就是為了使用緩存的。所以我們可以先說一下緩存的使用步驟:

緩存使用步驟

1、開啟基于注解的緩存,使用 @EnableCaching 標(biāo)識(shí)在 SpringBoot 的主啟動(dòng)類上。

2、標(biāo)注緩存注解即可

① 第一步:開啟基于注解的緩存,使用 @EnableCaching 標(biāo)注在 springboot 主啟動(dòng)類上

@EnableSwagger2
@EnableScheduling
@EnableFeignClients(basePackages = {"src.main.biz.smallProject.client","com.codingapi.tx"})
@EnableJpaRepositories(basePackages = {"src.main.biz.smallProject.web.*.dao","src.main.newgrand.framework.common.dao" })
@EntityScan(basePackages = { "src.main.biz.smallProject.web.*.entity","src.main.newgrand.framework.common.domain"})
@EnableCaching
public class StartApp {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(StartApp.class);
        new SpringUtil().setApplicationContext(context);
    }
}

② 第二步:標(biāo)注緩存注解

package src.main.biz.smallProject.web.cost.service.impl;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import src.main.biz.smallProject.utils.CollectionUtils;
import src.main.biz.smallProject.web.construct.form.IdsForm;
import src.main.biz.smallProject.web.cost.dao.BusinessScopeJPA;
import src.main.biz.smallProject.web.cost.entity.BusinessScopeEntity;
import src.main.biz.smallProject.web.cost.entity.QBusinessScopeEntity;
import src.main.biz.smallProject.web.cost.form.BusinessScopeForm;
import src.main.biz.smallProject.web.cost.form.BusinessScopeQueryForm;
import src.main.biz.smallProject.web.cost.service.BusinessScopeService;
import src.main.biz.smallProject.web.cost.vo.BusinessScopeVO;
import src.main.newgrand.framework.common.constants.PageData;
import src.main.newgrand.framework.common.exception.BusinessException;
import src.main.newgrand.framework.common.service.impl.BaseServiceImpl;
import src.main.newgrand.framework.common.utils.ResultRes;
import java.time.LocalDateTime;
import java.util.List;
import static src.main.biz.smallProject.redis.CacheConstants.BUSINESS_SCOPE_CACHE;
/**
 * @Description
 * @Author    yql
 * @Date 2022-05-10 10:44:29 */
@Service
public class BusinessScopeServiceImpl extends BaseServiceImpl<BusinessScopeJPA, BusinessScopeEntity, BusinessScopeVO> implements BusinessScopeService {
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    QBusinessScopeEntity qBusinessScopeEntity = QBusinessScopeEntity.businessScopeEntity;
    @Autowired
    private BusinessScopeService businessScopeService;
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    @CacheEvict(cacheNames = {BUSINESS_SCOPE_CACHE}, allEntries = true)
    public ResultRes add(BusinessScopeForm form) {
        BusinessScopeEntity businessScopeEntity = new BusinessScopeEntity();
        BeanUtils.copyProperties(form,businessScopeEntity);
        businessScopeService.save(businessScopeEntity);
        return ResultRes.success();
    }
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    @CacheEvict(cacheNames = {BUSINESS_SCOPE_CACHE}, allEntries = true)
    public ResultRes update(BusinessScopeForm form) {
        BusinessScopeEntity businessScopeEntity = findById(form.getPhid());
        if(businessScopeEntity == null){
            throw new BusinessException("數(shù)據(jù)不存在,請檢查!");
        }
        BeanUtils.copyProperties(form,businessScopeEntity);
        businessScopeService.updateSelectiveById(businessScopeEntity);
        return ResultRes.success();
    }
    @Override
    @Cacheable(cacheNames = BUSINESS_SCOPE_CACHE, key = "{ " + "#root.methodName, #form.status}", unless = "#result == null")
    public ResultRes<PageData> list(BusinessScopeQueryForm form) {
        long currPage = form.getCurrent();
        long size = form.getSize();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qBusinessScopeEntity.phDelflag.eq(0L));
        if(form.getStatus() != null){
            booleanBuilder.and(qBusinessScopeEntity.status.eq(form.getStatus()));
        }
        QueryResults<BusinessScopeVO> results = jpaQueryFactory
                .select(Projections.bean(
                        BusinessScopeVO.class,
                        qBusinessScopeEntity.phid,
                        qBusinessScopeEntity.name,
                        qBusinessScopeEntity.status))
                .from(qBusinessScopeEntity)
                .where(booleanBuilder)
                .orderBy(qBusinessScopeEntity.phInsertDt.desc())
                .offset((currPage - 1) * size)
                .limit(size).fetchResults();
        PageData pageData = new PageData(results.getResults(), results.getTotal(), size, currPage);
        return ResultRes.success(pageData);
    }
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    @CacheEvict(cacheNames = {BUSINESS_SCOPE_CACHE}, allEntries = true)
    public ResultRes deleteData(IdsForm form) {
        List<Long> ids = form.getIds();
        List<BusinessScopeEntity> businessScopeEntityList = queryFactory.selectFrom(qBusinessScopeEntity)
                .where(qBusinessScopeEntity.phid.in(ids).and(qBusinessScopeEntity.phDelflag.eq(0L)))
                .fetch();
        if(CollectionUtils.isEmpty(businessScopeEntityList)){
            throw new BusinessException("數(shù)據(jù)不存在,請檢查!");
        }
        queryFactory.update(qBusinessScopeEntity)
                .set(qBusinessScopeEntity.phDelflag, 1L)
                .set(qBusinessScopeEntity.phUpdateDt, LocalDateTime.now())
                .where(qBusinessScopeEntity.phid.in(ids))
                .execute();
        return ResultRes.success();
    }
}

常用屬性說明

cacheNames/value :用來指定緩存組件的名字

key :緩存數(shù)據(jù)時(shí)使用的 key,可以用它來指定。默認(rèn)是使用方法參數(shù)的值。(這個(gè) key 你可以使用 spEL 表達(dá)式來編寫)

keyGenerator :key 的生成器。 key 和 keyGenerator 二選一使用

cacheManager :可以用來指定緩存管理器。從哪個(gè)緩存管理器里面獲取緩存。

condition :可以用來指定符合條件的情況下才緩存

unless :否定緩存。當(dāng) unless 指定的條件為 true ,方法的返回值就不會(huì)被緩存。當(dāng)然你也可以獲取到結(jié)果進(jìn)行判斷。(通過 #result 獲取方法結(jié)果)

sync :是否使用異步模式。

spEL 編寫 key

前面說過,緩存的 key 支持使用 spEL 表達(dá)式去編寫,下面總結(jié)一下使用 spEL 去編寫 key 可以用的一些元數(shù)據(jù):

以上就是詳解如何使用SpringBoot的緩存@Cacheable的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot緩存@Cacheable的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 解決spring-boot 打成jar包后 啟動(dòng)時(shí)指定參數(shù)無效的問題

    解決spring-boot 打成jar包后 啟動(dòng)時(shí)指定參數(shù)無效的問題

    這篇文章主要介紹了解決spring-boot 打成jar包后 啟動(dòng)時(shí)指定參數(shù)無效的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • SpringBoot整合SpringSecurity認(rèn)證與授權(quán)

    SpringBoot整合SpringSecurity認(rèn)證與授權(quán)

    在項(xiàng)目開發(fā)中,權(quán)限認(rèn)證是很重要的,尤其是一些管理類的系統(tǒng),對(duì)于權(quán)限要求更為嚴(yán)格,本文主要介紹了SpringBoot整合SpringSecurity認(rèn)證與授權(quán),感興趣的可以了解一下
    2023-11-11
  • 探討Java驗(yàn)證碼制作(下篇)

    探討Java驗(yàn)證碼制作(下篇)

    這篇文章主要介紹了探討Java驗(yàn)證碼制作(下篇)的相關(guān)資料,需要的朋友可以參考下
    2016-05-05
  • Java超詳細(xì)介紹抽象類與接口的使用

    Java超詳細(xì)介紹抽象類與接口的使用

    在類中沒有包含足夠的信息來描繪一個(gè)具體的對(duì)象,這樣的類稱為抽象類,接口是Java中最重要的概念之一,它可以被理解為一種特殊的類,不同的是接口的成員沒有執(zhí)行體,是由全局常量和公共的抽象方法所組成,本文給大家介紹Java抽象類和接口,感興趣的朋友一起看看吧
    2022-05-05
  • Spring MVC 請求處理流程步驟詳解

    Spring MVC 請求處理流程步驟詳解

    這篇文章主要介紹了Spring MVC 請求處理流程詳解,本文分步驟結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧
    2025-04-04
  • 深入理解Java注解的使用方法

    深入理解Java注解的使用方法

    這篇文章主要為大家詳細(xì)介紹了Java注解的使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • 基于SpringBoot整合SSMP案例(開啟日志與分頁查詢條件查詢功能實(shí)現(xiàn))

    基于SpringBoot整合SSMP案例(開啟日志與分頁查詢條件查詢功能實(shí)現(xiàn))

    這篇文章主要介紹了基于SpringBoot整合SSMP案例(開啟日志與分頁查詢條件查詢功能實(shí)現(xiàn)),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋參考下吧
    2023-11-11
  • MyBatis-Plus數(shù)據(jù)權(quán)限插件的簡單使用

    MyBatis-Plus數(shù)據(jù)權(quán)限插件的簡單使用

    在MyBatis-Plus中,通過DataPermissionInterceptor插件實(shí)現(xiàn)數(shù)據(jù)權(quán)限控制,首先需要?jiǎng)?chuàng)建自定義注解和處理類,利用JSQLParser庫動(dòng)態(tài)修改SQL,實(shí)現(xiàn)按角色權(quán)限過濾數(shù)據(jù),配置類中注冊攔截器,確保只有授權(quán)用戶能訪問指定數(shù)據(jù),感興趣的可以了解一下
    2024-10-10
  • Java spring單點(diǎn)登錄系統(tǒng)

    Java spring單點(diǎn)登錄系統(tǒng)

    這篇文章主要介紹了Java spring單點(diǎn)登錄系統(tǒng),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-09-09
  • 在SpringBoot下讀取自定義properties配置文件的方法

    在SpringBoot下讀取自定義properties配置文件的方法

    這篇文章主要介紹了在SpringBoot下讀取自定義properties配置文件的方法,文中涉及到了Spring-boot中讀取config配置文件的兩種方式,需要的朋友可以參考下
    2017-12-12

最新評(píng)論