打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
spring-boot中配置和使用Caffeine Cache
  本地缓存,之前一直用Guava Cache,最近spring-boot推荐使用Caffeine Cache。
主要的三种本地缓存性能对比:


简单几步,就可以在spring-boot中配置和使用Caffeine Cache:

1、引入依赖:
  1. <!-- local cache -->  
  2. <dependency>  
  3.     <groupId>org.springframework.boot</groupId>  
  4.     <artifactId>spring-boot-starter-cache</artifactId>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>com.github.ben-manes.caffeine</groupId>  
  8.     <artifactId>caffeine</artifactId>  
  9. </dependency>  

2、配置:
有两种方法:
- application.yml配置文件中配置:
  - 优点:简单
  - 缺点:无法针对每个cache配置不同的参数,比如过期时长、最大容量
- 配置类中配置
  - 优点:可以针对每个cache配置不同的参数,比如过期时长、最大容量
  - 缺点:要写一点代码

2.1、配置文件中直接配置:
  1. spring:  
  2.   cache:  
  3.     type: CAFFEINE  
  4.     cache-names:  
  5.       - getPersonById  
  6.       - name2  
  7.     caffeine:  
  8.       spec: maximumSize=500,expireAfterWrite=5s  

然后还要在主类中加上@EnableCaching注解:
  1. @SpringBootApplication  
  2. @EnableScheduling  
  3. @EnableCaching  
  4. public class MySpringBootApplication  

2.2、另外一种更灵活的方法是在配置类中配置:

  1. package com.xjj.config;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.concurrent.TimeUnit;  
  5.   
  6. import org.springframework.cache.CacheManager;  
  7. import org.springframework.cache.annotation.EnableCaching;  
  8. import org.springframework.cache.caffeine.CaffeineCache;  
  9. import org.springframework.cache.support.SimpleCacheManager;  
  10. import org.springframework.context.annotation.Bean;  
  11. import org.springframework.context.annotation.Configuration;  
  12. import org.springframework.context.annotation.Primary;  
  13.   
  14. import com.github.benmanes.caffeine.cache.Caffeine;  
  15.   
  16.   
  17. /** 
  18.  * Cache配置類,用于缓存数据 
  19.  * @author XuJijun 
  20.  * 
  21.  */  
  22. @Configuration  
  23. @EnableCaching  
  24. public class CacheConfig {  
  25.   
  26.     public static final int DEFAULT_MAXSIZE = 50000;  
  27.     public static final int DEFAULT_TTL = 10;  
  28.       
  29.     /** 
  30.      * 定義cache名稱、超時時長(秒)、最大容量 
  31.      * 每个cache缺省:10秒超时、最多缓存50000条数据,需要修改可以在构造方法的参数中指定。 
  32.      */  
  33.     public enum Caches{  
  34.         getPersonById(5), //有效期5秒  
  35.         getSomething, //缺省10秒  
  36.         getOtherthing(300, 1000), //5分钟,最大容量1000  
  37.         ;  
  38.           
  39.         Caches() {  
  40.         }  
  41.   
  42.         Caches(int ttl) {  
  43.             this.ttl = ttl;  
  44.         }  
  45.   
  46.         Caches(int ttl, int maxSize) {  
  47.             this.ttl = ttl;  
  48.             this.maxSize = maxSize;  
  49.         }  
  50.           
  51.         private int maxSize=DEFAULT_MAXSIZE;    //最大數量  
  52.         private int ttl=DEFAULT_TTL;        //过期时间(秒)  
  53.           
  54.         public int getMaxSize() {  
  55.             return maxSize;  
  56.         }  
  57.         public int getTtl() {  
  58.             return ttl;  
  59.         }  
  60.     }  
  61.       
  62.     /** 
  63.      * 创建基于Caffeine的Cache Manager 
  64.      * @return 
  65.      */  
  66.     @Bean  
  67.     @Primary  
  68.     public CacheManager caffeineCacheManager() {  
  69.         SimpleCacheManager cacheManager = new SimpleCacheManager();  
  70.           
  71.         ArrayList<CaffeineCache> caches = new ArrayList<CaffeineCache>();  
  72.         for(Caches c : Caches.values()){  
  73.             caches.add(new CaffeineCache(c.name(),   
  74.                 Caffeine.newBuilder().recordStats()  
  75.                 .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)  
  76.                 .maximumSize(c.getMaxSize())  
  77.                 .build())  
  78.             );  
  79.         }  
  80.           
  81.         cacheManager.setCaches(caches);  
  82.   
  83.         return cacheManager;  
  84.     }  
  85.       
  86. }  

3、代码中使用:

  1. package com.xjj.service;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.cache.annotation.Cacheable;  
  7. import org.springframework.stereotype.Service;  
  8.   
  9. import com.xjj.dao.PersonDAO;  
  10. import com.xjj.entity.Person;  
  11.   
  12. @Service  
  13. public class PersonService {  
  14.     protected final Logger logger = LoggerFactory.getLogger(this.getClass());  
  15.       
  16.     @Autowired  
  17.     private PersonDAO personDao;  
  18.       
  19.   
  20.     /** 
  21.      * 根据id获取Person对象,使用缓存 
  22.      * @param id 
  23.      * @return Person对象 
  24.      */  
  25.     @Cacheable(value="getPersonById", sync=true)  
  26.     public Person getPersonById(int id){  
  27.         logger.debug("getting data from database, personId={}", id);  
  28.         return personDao.getPersonById(id);  
  29.     }  
  30.       
  31. }  

4、测试:

  1. @Autowired  
  2. PersonService personService;  
  3.   
  4. @Test  
  5. public void localCacheTest() throws JsonProcessingException, InterruptedException{  
  6.     System.out.println("第一次:"); //从数据库中获取  
  7.     Person p = personService.getPersonById(2);  
  8.     logger.info("1st time: {}", objectMapper.writeValueAsString(p));  
  9.       
  10.     System.out.println("第二次:"); //从缓存中获取  
  11.     p = personService.getPersonById(2);  
  12.     logger.info("2nd time: {}", objectMapper.writeValueAsString(p));  
  13.       
  14.     Thread.sleep(5000);  
  15.       
  16.     System.out.println("第三次:"); //5秒钟超时后,从数据库中获取  
  17.     p = personService.getPersonById(2);  
  18.     logger.info("3rd time: {}", objectMapper.writeValueAsString(p));  
  19.   
  20.     System.out.println("第四次:"); //从缓存中获取  
  21.     p = personService.getPersonById(2);  
  22.     logger.info("4th time: {}", objectMapper.writeValueAsString(p));  
  23.   
  24. }  

测试结果:

[plain] view plain copy
  1. 第一次:  
  2. 2016-11-02 17:11:13,105:DEBUG main (PersonService.java:27) - getting data from database, personId=2  
  3. 2016-11-02 17:11:13,150:INFO main (HikariDataSource.java:93) - HikariPool-1 - Started.  
  4. 2016-11-02 17:11:13,523:DEBUG main (BaseJdbcLogger.java:145) - ==>  Preparing: SELECT id, first_name AS firstName, last_name AS lastName, birth_date AS birthDate, sex, phone_no AS phoneNo FROM test.t_person WHERE id=?;   
  5. 2016-11-02 17:11:13,554:DEBUG main (BaseJdbcLogger.java:145) - ==> Parameters: 2(Integer)  
  6. 2016-11-02 17:11:13,572:TRACE main (BaseJdbcLogger.java:151) - <==    Columns: id, firstName, lastName, birthDate, sex, phoneNo  
  7. 2016-11-02 17:11:13,573:TRACE main (BaseJdbcLogger.java:151) - <==        Row: 2, 八, 李, 2015-08-07, F, 13625896321  
  8. 2016-11-02 17:11:13,582:DEBUG main (BaseJdbcLogger.java:145) - <==      Total: 1  
  9. 2016-11-02 17:11:13,665:INFO main (MySpringBootApplicationTests.java:149) - 1st time: {"id":2,"firstName":"八","lastName":"李","birthDate":1438876800000,"sex":"F","phoneNo":"13625896321"}  
  10. 第二次:  
  11. 2016-11-02 17:11:13,666:INFO main (MySpringBootApplicationTests.java:153) - 2nd time: {"id":2,"firstName":"八","lastName":"李","birthDate":1438876800000,"sex":"F","phoneNo":"13625896321"}  
  12. 第三次:  
  13. 2016-11-02 17:11:18,668:DEBUG main (PersonService.java:27) - getting data from database, personId=2  
  14. 2016-11-02 17:11:18,669:DEBUG main (BaseJdbcLogger.java:145) - ==>  Preparing: SELECT id, first_name AS firstName, last_name AS lastName, birth_date AS birthDate, sex, phone_no AS phoneNo FROM test.t_person WHERE id=?;   
  15. 2016-11-02 17:11:18,670:DEBUG main (BaseJdbcLogger.java:145) - ==> Parameters: 2(Integer)  
  16. 2016-11-02 17:11:18,671:TRACE main (BaseJdbcLogger.java:151) - <==    Columns: id, firstName, lastName, birthDate, sex, phoneNo  
  17. 2016-11-02 17:11:18,672:TRACE main (BaseJdbcLogger.java:151) - <==        Row: 2, 八, 李, 2015-08-07, F, 13625896321  
  18. 2016-11-02 17:11:18,672:DEBUG main (BaseJdbcLogger.java:145) - <==      Total: 1  
  19. 2016-11-02 17:11:18,673:INFO main (MySpringBootApplicationTests.java:159) - 3rd time: {"id":2,"firstName":"八","lastName":"李","birthDate":1438876800000,"sex":"F","phoneNo":"13625896321"}  
  20. 第四次:  
  21. 2016-11-02 17:11:18,674:INFO main (MySpringBootApplicationTests.java:163) - 4th time: {"id":2,"firstName":"八","lastName":"李","birthDate":1438876800000,"sex":"F","phoneNo":"13625896321"}  

Perfect!!!

完整的源代码:https://github.com/xujijun/my-spring-boot







本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
temp1
万字长文聊缓存(下)- 应用级缓存
springboot+mybatis集成自定义缓存ehcache用法笔记
注释驱动的 Spring cache 缓存介绍
Spring cache 缓存介绍
MyBatis注解方式之@Update/@Delete返回成功的条数进行成功校验
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服