国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - 使用Spring Cache設(shè)置緩存條件操作

使用Spring Cache設(shè)置緩存條件操作

2021-12-31 13:14梁云亮 Java教程

這篇文章主要介紹了使用Spring Cache設(shè)置緩存條件操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Spring Cache設(shè)置緩存條件

原理

從Spring3.1開始,Spring框架提供了對Cache的支持,提供了一個對緩存使用的抽象,通過在既有代碼中添加少量它定義的各種 annotation,即能夠達(dá)到緩存方法的返回對象的作用。

提供的主要注解有@Cacheable、@CachePut、@CacheEvict和@Caching,具體見下表:

注解 說明
@Cacheable 可以標(biāo)注在類或方法上:標(biāo)注在方法上表示該方法支持?jǐn)?shù)據(jù)緩存;標(biāo)在類上表示該類的所有方法都支持?jǐn)?shù)據(jù)緩存。 具體功能:在執(zhí)行方法體之前,檢查緩存中是否有相同key值的緩存存在,如果存在對應(yīng)的緩存,直接返回緩存中的值;如果不存在對應(yīng)的緩存,則執(zhí)行相應(yīng)的方法體獲取數(shù)據(jù),并將數(shù)據(jù)存儲到緩存中。
@CachePut 可以標(biāo)注在類或方法上,表示支持?jǐn)?shù)據(jù)緩存。 具體功能:在方法執(zhí)行前不會檢查緩存中是否存在相應(yīng)的緩存,而是每次都會執(zhí)行方法體,并將方法執(zhí)行結(jié)果存儲到緩存中,如果相應(yīng)key值的緩存存在,則更新key對應(yīng)的value值。
@CacheEvict 可以標(biāo)注在類或方法上,用于清除相應(yīng)key值的緩存。
@Caching 可以標(biāo)注在類或方法上,它有三個屬性cacheable、put、evict分別用于指定@Cacheable、@CachePut和@CacheEvict

當(dāng)需要在類上或方法上同時使用多個注解時,可以使用@Caching,如:

?
1
@Caching(cacheable=@Cacheable("User"), evict = {@CacheEvict("Member"), @CacheEvict(value = "Customer", allEntries = true)})

@Cacheable的常用屬性及說明

如下表所示:

@Cacheable屬性 說明
key 表示緩存的名稱,必須指定且至少要有一個值,比如:@Cacheable(value=“Dept”)或@Cacheable(value={“Dept”,“Depts”})
condition 表示是否需要緩存,默認(rèn)為空,表示所有情況都會緩存。通過SpEL表達(dá)式來指定,若condition的值為true則會緩存,若為false則不會緩存,如@Cacheable(value=“Dept”,key="‘deptno_'+# deptno “,condition=”#deptno<=40")
value 表示緩存的key,支持SpEL表達(dá)式,如@Cacheable(value=“Dept”,key="‘deptno_' +#deptno"),可以不指定值,如果不指定,則缺省按照方法的所有參數(shù)進(jìn)行組合。除了上述使用方法參數(shù)作為key之外,Spring還提供了一個root對象用來生成key,使用方法如下表所示,其中"#root"可以省略。

Root對象

Root對象 說明
methodName 當(dāng)前方法名,比如#root.methodName
method 當(dāng)前方法,比如#root.method.name
target 當(dāng)前被調(diào)用的對象,比如#root.target
targetClass 當(dāng)前被調(diào)用的對象的class,比如#root.targetClass
args 當(dāng)前方法參數(shù)組成的數(shù)組,比如#root.args[0]
caches 當(dāng)前被調(diào)用的方法使用的緩存,比如#root.caches[0].name

@CachePut的常用屬性同@Cacheable

@CacheEvict的常用屬性如下表所示:

@CacheEvict屬性 說明
value 表示要清除的緩存名
key 表示需要清除的緩存key值,
condition 當(dāng)condition的值為true時才清除緩存
allEntries 表示是否需要清除緩存中的所有元素。默認(rèn)為false,表示不需要,當(dāng)指定了allEntries為true時,將忽略指定的key。
beforeInvocation 清除操作默認(rèn)是在方法成功執(zhí)行之后觸發(fā)的,即方法如果因為拋出異常而未能成功返回時不會觸發(fā)清除操作。使用beforeInvocation可以改變觸發(fā)清除操作的時間,當(dāng)該屬性值為true時,會在調(diào)用該方法之前清除緩存中的指定元素。


示例:設(shè)置當(dāng) dname 的長度大于3時才緩存

?
1
2
3
4
5
6
7
8
9
10
//條件緩存
@ResponseBody
@GetMapping("/getLocByDname")
@Cacheable(cacheNames = "dept", key = "#dname", condition = "#dname.length()>3")
public String getLocByDname(@RequestParam("dname") String dname) {//key動態(tài)參數(shù)
    QueryWrapper<Dept> queryMapper = new QueryWrapper<>();
    queryMapper.eq("dname", dname);
    Dept dept = deptService.getOne(queryMapper);
    return dept.getLoc();
}

示例:unless 即條件不成立時緩存

#result 代表返回值,意思是當(dāng)返回碼不等于 200 時不緩存,也就是等于 200 時才緩存。

?
1
2
3
4
5
6
7
8
9
10
11
12
@ResponseBody
@GetMapping("/getDeptByDname")
@Cacheable(cacheNames = "dept", key = "#dname", unless = "#result.code != 200")
public Result<Dept> getDeptByDname(@RequestParam("dname") String dname){//key動態(tài)參數(shù)
    QueryWrapper<Dept> queryMapper = new QueryWrapper<>();
    queryMapper.eq("dname", dname);
    Dept dept = deptService.getOne(queryMapper);
    if (dept == null)
        return ResultUtil.error(120, "dept is null");
    else
        return ResultUtil.success(dept);
}

Cache緩存配置

1、pom.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 反射工具類用于手動掃描指定包下的注解,根據(jù)defaultCache模塊增加ehcache緩存域(非Spring Cache必須)-->
<!-- https://mvnrepository.com/artifact/org.reflections/reflections -->
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.11</version>
</dependency>

2、Ehcache配置文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?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="java.io.tmpdir" />
    <!--
        name:緩存名稱。
        maxElementsInMemory:緩存最大個數(shù)。
        eternal:對象是否永久有效,一但設(shè)置了,timeout將不起作用。
        timeToIdleSeconds:設(shè)置對象在失效前的允許閑置時間(單位:秒)。僅當(dāng)eternal=false對象不是永久有效時使用,可選屬性,默認(rèn)值是0,也就是可閑置時間無窮大。
        timeToLiveSeconds:設(shè)置對象在失效前允許存活時間(單位:秒)。最大時間介于創(chuàng)建時間和失效時間之間。僅當(dāng)eternal=false對象不是永久有效時使用,默認(rèn)是0.,也就是對象存活時間無窮大。
        overflowToDisk:當(dāng)內(nèi)存中對象數(shù)量達(dá)到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
        diskSpoolBufferSizeMB:這個參數(shù)設(shè)置DiskStore(磁盤緩存)的緩存區(qū)大小。默認(rèn)是30MB。每個Cache都應(yīng)該有自己的一個緩沖區(qū)。
        maxElementsOnDisk:硬盤最大緩存?zhèn)€數(shù)。
        diskPersistent:是否緩存虛擬機重啟期數(shù)據(jù) Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
        diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認(rèn)是120秒。
        memoryStoreEvictionPolicy:當(dāng)達(dá)到maxElementsInMemory限制時,Ehcache將會根據(jù)指定的策略去清理內(nèi)存。默認(rèn)策略是LRU(最近最少使用)。你可以設(shè)置為FIFO(先進(jìn)先出)或是LFU(較少使用)。
        clearOnFlush:內(nèi)存數(shù)量最大時是否清除。
    -->
    <!-- 默認(rèn)緩存 -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="200000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="600"
            memoryStoreEvictionPolicy="LRU" />
</ehcache>

3、配置類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
@Configuration
@EnableCaching
public class CustomConfiguration {
    /**
     * @see org.springframework.cache.interceptor.SimpleKeyGenerator
     * Generate a key based on the specified parameters.
     */
    public static Object generateKey(Object... params) {
        if (params.length == 0) {
            return SimpleKey.EMPTY;
        }
        if (params.length == 1) {
            Object param = params[0];
            if (param != null && !param.getClass().isArray()) {
                return param;
            }
        }
        return new SimpleKey(params);
    }
/**
 * 若將target作為key的一部分時,CGLIB動態(tài)代理可能導(dǎo)致重復(fù)緩存
 * 注意:返回的key一定要重寫hashCode()和toString(),防止key對象不一致導(dǎo)致的緩存無法命中
 * 例如:ehcache 底層存儲net.sf.ehcache.store.chm.SelectableConcurrentHashMap#containsKey
 */
    @Bean
    public KeyGenerator customKeyGenerator(){
        return (target, method, params) -> {
            final Object key = generateKey(params);
            StringBuffer buffer = new StringBuffer();
            buffer.append(method.getName());
            buffer.append("::");
            buffer.append(key.toString());
// 注意一定要轉(zhuǎn)為String,否則ehcache key對象可能不一樣,導(dǎo)致緩存無法命中
            return buffer.toString();
        };
    }
    /**
     * redis緩存管理器
     */
    @Bean
    @ConditionalOnBean(RedisConfiguration.class)
    @ConditionalOnProperty(prefix = "spring.cache", name = "type", havingValue = "redis",
            matchIfMissing = false)
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .entryTtl(Duration.ofMinutes(10));
        return RedisCacheManager
                .builder(RedisCacheWriter.lockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(config).build();
    }
/**
 * ehcache緩存管理器(默認(rèn))
 * default XML files {@link net.sf.ehcache.config.ConfigurationFactory#parseConfiguration()}
 */
    @Bean
    @ConditionalOnProperty(prefix = "spring.cache", name = "type", havingValue = "ehcache",
            matchIfMissing = true)
    public CacheManager ehcacheCacheManager() {
        net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.create();
        /**
         * 包掃描查找指定注解并將cacheNames添加到net.sf.ehcache.CacheManager(單例)
         */
        Reflections reflections = new Reflections("com.example.demo.service", new TypeAnnotationsScanner()
                , new SubTypesScanner(), new MethodAnnotationsScanner());
        Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(CacheConfig.class);
        for (Class<?> aClass : classesList) {
            final CacheConfig config = AnnotationUtils.findAnnotation(aClass, CacheConfig.class);
            if (config.cacheNames() != null && config.cacheNames().length > 0) {
                for (String cacheName : config.cacheNames()) {
                    cacheManager.addCacheIfAbsent(cacheName);
                }
            }
        }
        /**
         * 方法級別的注解 @Caching、@CacheEvict、@Cacheable、@CachePut,結(jié)合實際業(yè)務(wù)場景僅掃描@Cacheable即可
         */
        final Set<Method> methods = reflections.getMethodsAnnotatedWith(Cacheable.class);
        for (Method method : methods) {
            final Cacheable cacheable = AnnotationUtils.findAnnotation(method, Cacheable.class);
            if (cacheable.cacheNames() != null && cacheable.cacheNames().length > 0) {
                for (String cacheName : cacheable.cacheNames()) {
                    cacheManager.addCacheIfAbsent(cacheName);
                }
            }
        }
        EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
        ehCacheCacheManager.setCacheManager(cacheManager);
        return ehCacheCacheManager;
    }
}

4、示例

?
1
2
3
4
5
6
7
8
9
10
11
12
@Component
@CacheConfig(cacheNames = "XXXServiceImpl", keyGenerator = "customKeyGenerator")
public class XXXServiceImpl extends ServiceImpl<XXXMapper, XXXEntity> implements XXXService {
    @CacheEvict(allEntries = true)
    public void evictAllEntries() {}
    @Override
    @Cacheable
    public List<XXXEntity> findById(Long id) {
        return this.baseMapper.selectList(new QueryWrapper<XXXEntity>().lambda()
                .eq(XXXEntity::getId, id));
    }
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。

原文鏈接:https://hcshow.blog.csdn.net/article/details/119271227

延伸 · 閱讀

精彩推薦
  • Java教程Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決

    Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決

    這篇文章主要介紹了Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望...

    spcoder14552021-10-18
  • Java教程小米推送Java代碼

    小米推送Java代碼

    今天小編就為大家分享一篇關(guān)于小米推送Java代碼,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧...

    富貴穩(wěn)中求8032021-07-12
  • Java教程20個非常實用的Java程序代碼片段

    20個非常實用的Java程序代碼片段

    這篇文章主要為大家分享了20個非常實用的Java程序片段,對java開發(fā)項目有所幫助,感興趣的小伙伴們可以參考一下 ...

    lijiao5352020-04-06
  • Java教程升級IDEA后Lombok不能使用的解決方法

    升級IDEA后Lombok不能使用的解決方法

    最近看到提示IDEA提示升級,尋思已經(jīng)有好久沒有升過級了。升級完畢重啟之后,突然發(fā)現(xiàn)好多錯誤,本文就來介紹一下如何解決,感興趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    這篇文章主要介紹了Java使用SAX解析xml的示例,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程Java實現(xiàn)搶紅包功能

    Java實現(xiàn)搶紅包功能

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)搶紅包功能,采用多線程模擬多人同時搶紅包,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙...

    littleschemer13532021-05-16
  • Java教程xml與Java對象的轉(zhuǎn)換詳解

    xml與Java對象的轉(zhuǎn)換詳解

    這篇文章主要介紹了xml與Java對象的轉(zhuǎn)換詳解的相關(guān)資料,需要的朋友可以參考下...

    Java教程網(wǎng)2942020-09-17
  • Java教程Java8中Stream使用的一個注意事項

    Java8中Stream使用的一個注意事項

    最近在工作中發(fā)現(xiàn)了對于集合操作轉(zhuǎn)換的神器,java8新特性 stream,但在使用中遇到了一個非常重要的注意點,所以這篇文章主要給大家介紹了關(guān)于Java8中S...

    阿杜7482021-02-04
Weibo Article 1 Weibo Article 2 Weibo Article 3 Weibo Article 4 Weibo Article 5 Weibo Article 6 Weibo Article 7 Weibo Article 8 Weibo Article 9 Weibo Article 10 Weibo Article 11 Weibo Article 12 Weibo Article 13 Weibo Article 14 Weibo Article 15 Weibo Article 16 Weibo Article 17 Weibo Article 18 Weibo Article 19 Weibo Article 20 Weibo Article 21 Weibo Article 22 Weibo Article 23 Weibo Article 24 Weibo Article 25 Weibo Article 26 Weibo Article 27 Weibo Article 28 Weibo Article 29 Weibo Article 30 Weibo Article 31 Weibo Article 32 Weibo Article 33 Weibo Article 34 Weibo Article 35 Weibo Article 36 Weibo Article 37 Weibo Article 38 Weibo Article 39 Weibo Article 40
主站蜘蛛池模板: 婷婷久久一区 | 欧美日韩三区 | 黄网站涩免费蜜桃网站 | 看av网站| 亚洲片国产一区一级在线观看 | 国产精品久久久久久久久久久久久 | 成人3d动漫一区二区三区91 | 久久久精品视频免费观看 | 午夜看片 | 国产精品久久久久久久久大全 | 日韩欧美一区二区三区久久婷婷 | 国产午夜精品一区二区三区嫩草 | 羞羞视频免费看 | 在线亚洲精品 | 精品国产三级 | 亚洲一区电影 | 久久aⅴ国产欧美74aaa | 亚洲综合二区 | a在线观看 | 欧美91 | 国产亚洲精品美女久久久久久久久久 | 欧美日本韩国一区二区三区 | 国产视频黄在线观看 | 国产成人精品一区二 | 在线精品国产 | xvideos.蜜桃一区二区 | 国产精品美女久久久久久久网站 | 久久91精品 | 国产一区二区三区久久 | 久久中文字幕一区二区三区 | 日本中文字幕在线播放 | 午夜爽爽| 黄色综合 | 日韩在线观看一区 | 天天草夜夜 | 日韩成人免费 | 亚洲精品视频在线 | 日韩av在线中文字幕 | 久久精品久久久久久 | 不卡视频一区 | 欧美一级片免费在线观看 |