栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot集成caffeine本地缓存

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot集成caffeine本地缓存

pom:

        
            com.github.ben-manes.caffeine
            caffeine
            2.9.3
        
CacheConfig:
package com.sdkj.mtest.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {

    @Bean
    public Cache caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                .build();
    }
}
UserInfo:
package com.sdkj.mtest.entity;

import lombok.Data;

@Data
public class UserInfo {
    private Integer id;
    private String name;
}
TestController:
package com.sdkj.mtest.controller;

import com.github.benmanes.caffeine.cache.Cache;
import com.sdkj.mtest.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private Cache caffeineCache;

    @GetMapping("/test")
    public void test() {

        UserInfo userInfo = new UserInfo();
        userInfo.setId(1);
        userInfo.setName("张三");

        //添加缓存
        caffeineCache.put("userInfoList:1",userInfo);

        //读取缓存
        UserInfo cacheUserInfo = (UserInfo) caffeineCache.asMap().get(String.valueOf("userInfoList:1"));
        System.out.println("cacheUserInfo从缓存中读出的名称为==>"+cacheUserInfo.getName());

        //删除缓存
        caffeineCache.asMap().remove(String.valueOf("userInfoList:1"));

    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/859348.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号