美文网首页
springboo整合local cache

springboo整合local cache

作者: 彳亍口巴 | 来源:发表于2024-01-20 12:28 被阅读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);
        }
    

    相关文章

      网友评论

          本文标题:springboo整合local cache

          本文链接:https://www.haomeiwen.com/subject/swcsodtx.html