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

SpringBoot整合Caffeine使用示例

 更新時間:2024年07月04日 09:11:14   作者:謝林v  
Spring Boot 和 Caffeine 可以很容易地進(jìn)行整合,Caffeine 是一個現(xiàn)代化的 Java 緩存庫,提供了高性能和靈活的緩存策略,本文給大家介紹了SpringBoot整合Caffeine使用示例,需要的朋友可以參考下

簡單介紹

  • 在需要緩存的方法上使用@Cacheable注解來緩存方法的返回值:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Cacheable(cacheNames = "myCache", key = "#id")
    public String getExpensiveDataById(Integer id) {
        // 模擬耗時操作
        return "Some expensive data for id: " + id;
    }
}

getExpensiveDataById方法的結(jié)果將根據(jù)傳入的id被緩存。如果同樣的id再次請求,將直接從緩存中獲取結(jié)果,而不會執(zhí)行方法體中的耗時操作。

cacheNames屬性定義了緩存的邏輯名稱,它是一個字符串。在Spring的緩存框架中,這個名稱被用來唯一標(biāo)識一個緩存區(qū)域。

緩存區(qū)域是底層緩存存儲中的一部分,可以把它想象成一個命名的存儲空間,其中可以存放多個鍵值對。每個緩存名稱對應(yīng)一個緩存區(qū)域。

緩存區(qū)域內(nèi)部以鍵值對的形式存儲數(shù)據(jù)。每個鍵值對包含一個鍵(key)和相應(yīng)的值(value)。

  • 使用@CacheEvict注解手動清除緩存。
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @CacheEvict(cacheNames = "myCache", allEntries = true)
    public void clearMyCache() {
        // 清除名為myCache的緩存中的所有項
    }
}

示例

新建一個Spring項目。Caffeine已經(jīng)作為默認(rèn)的緩存庫被包含在Spring Boot的依賴中,所以通常不需要顯式添加Caffeine的依賴。

配置相關(guān)屬性

# application.properties 示例
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=30m

Controller

@RestController
@Slf4j
public class MyController {
    @Resource
    private MyService myService;

    @GetMapping("/cache")
    public String cache() {
        log.info("收到了增加緩存請求");
        return myService.getExpensiveDataById(1);
    }
    @GetMapping("/cache/del")
    public void delCache() {
        log.info("收到了刪除緩存請求");
        myService.deleteExpensiveDataById(1);
    }
}

Service

@Service
@Slf4j
public class MyService {

    @Cacheable(cacheNames = "myCache", key = "#id")
    public String getExpensiveDataById(Integer id) {
        // 模擬耗時操作
        log.info("執(zhí)行了操作");
        return "Some expensive data for id: " + id;
    }

    @CacheEvict(cacheNames = "myCache", key = "#id")
    public void deleteExpensiveDataById(Integer id) {
        // 模擬刪除操作
        log.info("執(zhí)行了刪除操作");
    }

}

測試步驟

1. 運(yùn)行項目,打開瀏覽器,輸入請求地址localhost:8080/cache,看到日志輸出如下:

2. 刷新地址,發(fā)現(xiàn)日志輸出如下:

3. 說明這次請求走了緩存 3. 輸入請求地址localhost:8080/cache/del,日志輸出如下

4. 再次請求地址lcoalhost:8080/cache,日志輸出如下

說明上一次的刪除緩存已經(jīng)起效果。

到此這篇關(guān)于SpringBoot整合Caffeine使用示例的文章就介紹到這了,更多相關(guān)SpringBoot整合Caffeine內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論