springboo整合local cache

1、引入對應(yīng)的依賴

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

2、添加緩存相關(guān)的常量(緩存名稱、緩存過期時(shí)間、緩存大?。?/p>

package com.example.mybatis.demos.web.common;

/**
 * 常量定義
 */
public class Constants {
    public static class LocalCache {
        public static final String CacheName = "my_local_cache_name";
        public static final int TTL = 10; // 緩存過期時(shí)間
        public static final int CAPACITY = 5000; // 緩存容量
    }
}

3、定義枚舉,多個(gè)緩存的話直接遍歷枚舉

package com.example.mybatis.demos.web.enums;

import com.example.mybatis.demos.web.common.Constants;
import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public enum CacheEnum {
    LOCALCACHE(Constants.LocalCache.CacheName,Constants.LocalCache.TTL,Constants.LocalCache.CAPACITY);
    private String name;
    private int ttl;
    private int capacity;

}

4、使用

@Cacheable(cacheNames = Constants.LocalCache.CacheName,key = "#id")
    @Override
    public Student getStudentByID(int id) {
        log.info("get info by id not from local cache={}",id);
        return studentMapper.getStudentByID(id);
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容