文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

springboot集成本地缓存Caffeine的三种使用方式(小结)

2024-04-02 19:55

关注

第一种方式(只使用Caffeine)

gradle添加依赖

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3'
    runtimeOnly 'mysql:mysql-connector-java'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    compile group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '2.8.4'
//    compile('org.springframework.boot:spring-boot-starter-cache')
}


编写配置类

package org.example.base.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
//@EnableCaching
public class CacheConfig {


    @Bean(value = "caffeineCache")
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(1000)
                // 缓存的最大条数
                .maximumSize(10000)
                .build();

    }

    @Bean(value = "caffeineCache2")
    public Cache<String, Object> caffeineCache2() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(120, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(1000)
                // 缓存的最大条数
                .maximumSize(10000)
                .build();

    }


}

测试

package org.example.base;

import com.github.benmanes.caffeine.cache.Cache;
import org.example.base.bean.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class BaseApplicationTests {

	@Qualifier("caffeineCache")
	@Autowired
    Cache<String, Object> cache;


	@Qualifier("caffeineCache2")
	@Autowired
	Cache<String, Object> cache2;

    @Test
    public void test() {
        User user = new User(1, "张三", 18);
        cache.put("123", user);
        User user1 = (User) cache.getIfPresent("123");
        assert user1 != null;
        System.out.println(user1.toString());
        User user2 = (User) cache2.getIfPresent("1234");
        System.out.println(user2 == null);
    }

}

输出

第二种方式(使用Caffeine和spring cache)

gradle添加依赖

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3'
    runtimeOnly 'mysql:mysql-connector-java'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    compile group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '2.8.4'
    compile('org.springframework.boot:spring-boot-starter-cache')
}

编写配置类

package org.example.base.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.ArrayList;



@Configuration
@EnableCaching
public class CacheConfig {


    public enum CacheEnum {
        
        FIRST_CACHE(300, 20000, 300),
        
        SECOND_CACHE(60, 10000, 200);

        private int second;
        private long maxSize;
        private int initSize;

        CacheEnum(int second, long maxSize, int initSize) {
            this.second = second;
            this.maxSize = maxSize;
            this.initSize = initSize;
        }

    }

    @Bean("caffeineCacheManager")
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ArrayList<CaffeineCache> caffeineCaches = new ArrayList<>();
        for (CacheEnum cacheEnum : CacheEnum.values()) {
            caffeineCaches.add(new CaffeineCache(cacheEnum.name(),
                    Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(cacheEnum.second))
                            .initialCapacity(cacheEnum.initSize)
                            .maximumSize(cacheEnum.maxSize).build()));
        }
        cacheManager.setCaches(caffeineCaches);
        return cacheManager;
    }

//    @Bean("FIRST_CACHE")
//    public Cache firstCache(CacheManager cacheManager) {
//        return cacheManager.getCache("FIRST_CACHE");
//    }
//
//    @Bean("SECOND_CACHE")
//    public Cache secondCache(CacheManager cacheManager) {
//        return cacheManager.getCache("SECOND_CACHE");
//    }

}

编写service层

package org.example.base;

import org.example.base.bean.User;
import org.example.base.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class BaseApplicationTests {

    @Autowired
    private UserService userService;

    @Test
    public void test() {
        User user = new User(123,"jack l",18);
        userService.setUser(user);
        System.out.println(userService.getUser("123"));
    }


}

测试

package org.example.base;

import org.example.base.bean.User;
import org.example.base.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class BaseApplicationTests {

    @Autowired
    private UserService userService;

    @Test
    public void test() {
        User user = new User(123,"jack l",18);
        userService.setUser(user);
        System.out.println(userService.getUser("123"));
    }


}

输出结果

第三种方式(使用Caffeine和spring cache)

package org.example.base.service.impl;

import org.example.base.bean.User;
import org.example.base.service.UserService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;



@Service
//@CacheConfig(cacheNames = "SECOND_CACHE",cacheManager = "caffeineCacheManager")
public class UserServiceImpl implements UserService {

    
    @Override
    @CachePut(key = "#user.getId()", value = "SECOND_CACHE", cacheManager = "caffeineCacheManager")
    public User setUser(User user) {
        System.out.println("已经存储进缓存了");
        return user;
    }

    @Override
    @CacheEvict(value = "SECOND_CACHE",cacheManager = "caffeineCacheManager")
    public void deleteUser(Integer id) {
        System.out.println("缓存删除了");
    }

    @Override
    @Cacheable(key = "#id", value = "SECOND_CACHE", cacheManager = "caffeineCacheManager")
    public User getUser(Integer id) {
        System.out.println("从数据库取值");
        //模拟数据库中的数据
       return null;
    }


}

测试

package org.example.base;

import org.example.base.bean.User;
import org.example.base.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class BaseApplicationTests {

    @Autowired
    private UserService userService;


    @Test
    public void test4(){
        User user1 = new User(123, "jack l", 18);
        userService.setUser(user1);
        System.out.println("从缓存中获取 "+userService.getUser(123));
        System.out.println(userService.getUser(123322222));
        userService.deleteUser(123);
        System.out.println(userService.getUser(123));

    }


}


输出结果

到此这篇关于springboot集成本地缓存Caffeine的三种使用方式(小结)的文章就介绍到这了,更多相关springboot集成本地缓存Caffeine内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯