springboo整合local cache

2024-01-20  本文已影响0人  彳亍口巴

1、引入对应的依赖

<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、添加缓存相关的常量(缓存名称、缓存过期时间、缓存大小)

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; // 缓存过期时间
        public static final int CAPACITY = 5000; // 缓存容量
    }
}

3、定义枚举,多个缓存的话直接遍历枚举

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);
    }
上一篇下一篇

猜你喜欢

热点阅读