亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring?Cache?集成?Caffeine實(shí)現(xiàn)項(xiàng)目緩存的示例

 更新時(shí)間:2021年12月24日 10:56:12   作者:Simon西蒙  
本文主要介紹了Spring?Cache?集成?Caffeine實(shí)現(xiàn)項(xiàng)目緩存的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

一、前言

Spring Cache本身是Spring框架中一個(gè)緩存體系的抽象實(shí)現(xiàn),本身不具備緩存能力,需要配合具體的緩存實(shí)現(xiàn)來(lái)完成,如Ehcache、Caffeine、Guava、Redis等。

二、緩存注解

  • @EnableCaching:開(kāi)啟緩存功能
  • @Cacheable:定義緩存,用于觸發(fā)緩存
  • @CachePut:定義更新緩存,觸發(fā)緩存更新
  • @CacheEvict:定義清楚緩存,觸發(fā)緩存清除
  • @Caching:組合定義多種緩存功能
  • @CacheConfig:定義公共設(shè)置,位于class之上

三、實(shí)戰(zhàn)操作

我選擇使用目前最受歡迎的Caffeine來(lái)作為具體的緩存實(shí)現(xiàn)方式,下面是一個(gè)demo:

1、依賴引入

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.8.6</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2、yaml配置

spring:
  cache:
    cache-names: USER
    caffeine:
      spec: initialCapacity=50,maximumSize=500,expireAfterWrite=5s
    type: caffeine

Caffeine配置說(shuō)明

  • initialCapacity=[integer]: 初始的緩存空間大小
  • maximumSize=[long]: 緩存的最大條數(shù)
  • maximumWeight=[long]: 緩存的最大權(quán)重
  • expireAfterAccess=[duration]: 最后一次寫(xiě)入或訪問(wèn)后經(jīng)過(guò)固定時(shí)間過(guò)期
  • expireAfterWrite=[duration]: 最后一次寫(xiě)入后經(jīng)過(guò)固定時(shí)間過(guò)期
  • refreshAfterWrite=[duration]: 創(chuàng)建緩存或者最近一次更新緩存后經(jīng)過(guò)固定的時(shí)間間隔,刷新緩存
  • weakKeys: 打開(kāi)key的弱引用
  • weakValues:打開(kāi)value的弱引用
  • softValues:打開(kāi)value的軟引用
  • recordStats:開(kāi)發(fā)統(tǒng)計(jì)功能

注意

  • expireAfterWrite和expireAfterAccess同事存在時(shí),以expireAfterWrite為準(zhǔn)。
  • maximumSize和maximumWeight不可以同時(shí)使用
  • weakValues和softValues不可以同時(shí)使用

3、開(kāi)啟緩存

4、模擬方法

service層

@Service
@Slf4j
public class CaffeineService {

    public static Map<String, String> map = new HashMap<>();

    static {
        map.put("1", "zhangsan");
        map.put("2", "lisi");
        map.put("3", "wangwu");
    }

    @Cacheable(value = "USER", key = "#id")
    public String getUser(String id) {
        log.info("getUser() run......");
        return map.get(id);
    }

    @CachePut(value = "USER", key = "#id")
    public String updateUser(String id, String name) {
        log.info("updateUser() run......");
        map.put(id, name);
        return map.toString();
    }

    @CacheEvict(value = "USER", key = "#id")
    public String delUser(String id) {
        log.info("delUser() run......");
        map.remove(id);
        return map.toString();
    }

}

controller層

@RestController
@RequestMapping("/cache")
@Slf4j
public class CaffeineController {

    @Autowired
    private CaffeineService caffeineService;

    @GetMapping("/user/{id}")
    public String getUser(@PathVariable String id) {
        long start = System.currentTimeMillis();
        String res = caffeineService.getUser(id);
        long end = System.currentTimeMillis();
        log.info("查詢耗時(shí):" + (end - start));
        return res;
    }

    @GetMapping("/user/{id}/{name}")
    public String updateUser(@PathVariable String id, @PathVariable String name) {
        return caffeineService.updateUser(id, name);
    }

    @DeleteMapping("/user/{id}")
    public String delUser(@PathVariable String id) {
        return caffeineService.delUser(id);
    }
}

5、測(cè)試

第一次查詢:


第二次查詢:


查詢耗時(shí)明顯小于第一次查詢,因?yàn)榈诙沃苯臃祷鼐彺妫俣忍嵘?/p>

執(zhí)行更新后再查詢:
會(huì)使緩存失效。會(huì)重新執(zhí)行查詢方法查詢


執(zhí)行刪除后再查詢:
會(huì)使緩存失效。會(huì)重新執(zhí)行查詢方法查詢

6、改造

上述通過(guò)yaml文件配置的方式不夠靈活,無(wú)法實(shí)現(xiàn)多種緩存策略,所以現(xiàn)在一般使用javaconfig的形式進(jìn)行配置。

下面是示例代碼:

@Configuration
public class CaffeineConfig {

    @Bean
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
        List<CaffeineCache> caffeineCaches = new ArrayList<>();
        for (CacheType cacheType : CacheType.values()) {
            caffeineCaches.add(new CaffeineCache(cacheType.name(),
                    Caffeine.newBuilder()
                            .expireAfterWrite(cacheType.getExpires(), TimeUnit.SECONDS)
                            .build()));
        }
        simpleCacheManager.setCaches(caffeineCaches);
        return simpleCacheManager;
    }
}
public enum CacheType {

    USER(5),
    TENANT(20);

    private int expires;

    CacheType(int expires) {
        this.expires = expires;
    }

    public int getExpires() {
        return expires;
    }

}

這樣我們就能對(duì)USER設(shè)置5秒消防時(shí)間,對(duì)TENANT設(shè)置20秒消亡時(shí)間,在實(shí)際項(xiàng)目中這種方式更加的靈活。

到此這篇關(guān)于Spring Cache 集成 Caffeine實(shí)現(xiàn)項(xiàng)目緩存的示例的文章就介紹到這了,更多相關(guān)Spring Cache Caffeine緩存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論