springboot集成caffeine本地缓存[亲测有效]

springboot集成caffeine本地缓存[亲测有效]pom:<dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId><version>2.9.3</version></dependency>CacheConfig:

大家好,欢迎来到IT知识分享网。

pom:

        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.9.3</version>
        </dependency>
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<String, Object> 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<String, Object> 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"));

    }

}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/24335.html

(0)
上一篇 2023-08-25 09:00
下一篇 2023-08-27 10:45

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信