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

作者:冬风孤立 时间:2021-06-29 07:00:40 

第一种方式(只使用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;

/**
* @author l
* @date Created in 2020/10/27 11:05
*/
@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);
   }

}

输出

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

第二种方式(使用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;

/**
* @author l
* @date Created in 2020/10/27 11:05
*/
@Configuration
@EnableCaching
public class CacheConfig {

public enum CacheEnum {
       /**
        * @date 16:34 2020/10/27
        * 第一个cache
        **/
       FIRST_CACHE(300, 20000, 300),
       /**
        * @date 16:35 2020/10/27
        * 第二个cache
        **/
       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"));
   }

}

输出结果

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

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

  • gradle依赖添加同方式二

  • 配置类添加方式同方式二

  • 编写service层

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;

/**
* @author l
* @date Created in 2020/10/23 14:47
*/
@Service
//@CacheConfig(cacheNames = "SECOND_CACHE",cacheManager = "caffeineCacheManager")
public class UserServiceImpl implements UserService {

/**
    * 使用@CachePut注解的方法,一定要有返回值,该注解声明的方法缓存的是方法的返回结果。
    * it always causes the
    * method to be invoked and its result to be stored in the associated cache
    **/
   @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的三种使用方式(小结)

来源:https://blog.csdn.net/qq_41921994/article/details/109313445

标签:springboot,本地缓存,Caffeine
0
投稿

猜你喜欢

  • java旋转二维数组实例

    2021-07-04 05:39:48
  • java Springboot实现教务管理系统

    2023-01-18 00:28:12
  • Intellij IDEA创建spring-boot项目的图文教程

    2022-06-15 01:09:59
  • java开发工作中对InheritableThreadLocal使用思考

    2023-11-24 21:46:44
  • 浅谈Unity脚本生命周期与执行顺序

    2022-05-22 00:47:34
  • Java中ThreadLocal避免内存泄漏的方法详解

    2023-04-02 12:51:42
  • java poi解析word的方法

    2023-08-28 07:31:28
  • Java中对AtomicInteger和int值在多线程下递增操作的测试

    2023-10-22 18:32:03
  • java序列化对象根据不同配置动态改变属性名的方法

    2022-10-06 11:31:09
  • mybatis报错元素内容必须由格式正确的字符数据或标记组成异常的解决办法

    2023-01-10 15:46:37
  • Java中JavaBean对象和Map的互相转换方法实例

    2021-07-12 04:46:05
  • slf4j与jul、log4j1、log4j2、logback的集成原理

    2023-01-31 18:01:47
  • C#获取上个月第一天和最后一天日期的方法

    2023-02-22 07:33:44
  • 基于Java实现收发电子邮件功能

    2021-08-23 17:30:14
  • 怎么把本地jar包放入本地maven仓库和远程私服仓库

    2023-12-05 20:13:00
  • springboot jpa 延迟加载问题的2种解决

    2021-10-14 03:05:20
  • MyEclipse设置Console输出到文件的实现方法

    2022-01-14 10:37:03
  • 基于多网卡环境下Eureka服务注册IP的选择问题

    2022-09-16 17:59:15
  • SpringBoot集成支付宝沙箱支付的实现示例

    2023-10-31 19:22:20
  • 解析Android中string-array数据源的简单使用

    2022-12-19 10:06:53
  • asp之家 软件编程 m.aspxhome.com