37 Star 326 Fork 104

aizuda/aizuda-components

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

aizuda-cache

配置 application.yml 文件

aizuda:
  redis:
    enable: true
    mode: single # 可选值:single, cluster, sentinel
    host: localhost
    port: 6379
    password: yourPassword
    database: 0
    # 集群模式
    #      nodes:
    #        - node1:6379
    #        - node2:6379
    # 哨兵模式
    #      sentinelMaster: mymaster
    #      sentinels:
    #        - 127.0.0.1:26379
    #        - 127.0.0.1:26380
    cacheConfigs:
      defaultCache:
        ttl: 600 # 10 分钟
        keyPrefix: "default:"
      myCache:
        ttl: 60 # 1 分钟
        keyPrefix: "my:"

调用使用 @Cacheable 注解

// 需要引入依赖 implementation("org.springframework.boot:spring-boot-starter-data-redis")
@Service
public class MyService {
    @Resource
    private RedisTemplateCache redisTemplateCache;

    @Cacheable(value = "myCache", key = "#id")
    public String getDataFromRedis(Long id) {
        // 不使用注解 @Cacheable 调用 redisTemplateCache 操作
        return "Some data";
    }
}

缓存错误自定义处理器

@Bean
public CacheErrorHandler errorHandler() {
    return new CacheErrorHandler() {
        ...
    };
}

使用 LocalCacheCaffeine 案例

import java.util.concurrent.TimeUnit;

// 需要引入依赖 implementation("com.github.ben-manes.caffeine:caffeine")
public class UserService {

    // 最多缓存 500 个用户,过期时间为 10 分钟
    private static final LocalCacheCaffeine<String, String> userCache = new LocalCacheCaffeine<>(500, 10, TimeUnit.MINUTES);

    public String getUserInfo(String userId) {
        // 尝试从缓存中获取用户信息
        String userInfo = userCache.get(userId);

        if (userInfo == null) {
            // 模拟从数据库加载用户数据
            userInfo = loadUserFromDb(userId);
            // 缓存加载的数据
            userCache.set(userId, userInfo);
        }

        return userInfo;
    }

    private String loadUserFromDb(String userId) {
        // 模拟从数据库加载用户信息
        System.out.println("Loading user from database...");
        return "User-" + userId;
    }

    public static void main(String[] args) {
        UserService service = new UserService();

        // 第一次访问时,缓存为空,从数据库加载
        System.out.println(service.getUserInfo("user1"));

        // 第二次访问时,从缓存获取
        System.out.println(service.getUserInfo("user1"));
    }
}

  • 使用 CacheLoader 实现自动加载功能
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.LoadingCache;

public class CaffeineUtilWithLoader {

    private LoadingCache<String, String> cache;

    public CaffeineUtilWithLoader() {
        cache = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .maximumSize(1000)
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String key) throws Exception {
                        // 自动加载逻辑,这里模拟从数据库加载
                        return loadFromDatabase(key);
                    }
                });
    }

    // 获取缓存,如果缓存中不存在则自动加载
    public String get(String key) {
        try {
            return cache.get(key);
        } catch (Exception e) {
            return null;
        }
    }

    private String loadFromDatabase(String key) {
        // 模拟从数据库加载数据
        System.out.println("Loading data from database for key: " + key);
        return "Value-for-" + key;
    }
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/aizuda/aizuda-components.git
git@gitee.com:aizuda/aizuda-components.git
aizuda
aizuda-components
aizuda-components
master

搜索帮助