副标题[/!--empirenews.page--]
                        摘要
日常开发中,需要用到各种各样的框架来实现API、系统的构建。作为程序员,除了会使用框架还必须要了解框架工作的原理。这样可以便于我们排查问题,和自定义的扩展。那么如何去学习框架呢。通常我们通过阅读文档、查看源码,然后又很快忘记。始终不能融汇贯通。本文主要基于Spring Cache扩展为例,介绍如何进行高效的源码阅读。 
SpringCache的介绍
为什么以Spring Cache为例呢,原因有两个 
    - Spring框架是web开发最常用的框架,值得开发者去阅读代码,吸收思想
 
    - 缓存是企业级应用开发必不可少的,而随着系统的迭代,我们可能会需要用到内存缓存、分布式缓存。那么Spring Cache作为胶水层,能够屏蔽掉我们底层的缓存实现。
 
 
一句话解释Spring Cache: 通过注解的方式,利用AOP的思想来解放缓存的管理。 
step1 查看文档
首先通过查看官方文档,概括了解Spring Cache 
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html 
重点两点 
1. 两个接口抽象 Cache,CacheManager,具体的实现都是基于这两个抽象实现。 
典型的SPI机制,和eat your dog food。当需要提供接口给外部调用,首先自己内部的实现也必须基于同样一套抽象机制 
- The cache abstraction does not provide an actual store and relies on abstraction materialized by the org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces. 
 
  
2. Spring Cache提供了这些缓存的实现,如果没有一种CacheManage,或者CacheResolver,会按照指定的顺序去实现 
- If you have not defined a bean of type CacheManager or a CacheResolver named cacheResolver (see CachingConfigurer), Spring Boot tries to detect the following providers (in the indicated order): 
 - 1.Generic 
 - 2.JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others) 
 - 3.EhCache 2.x 
 - 4.Hazelcast 
 - 5.Infinispan 
 - 6.Couchbase 
 - 7.Redis 
 - 8.Caffeine 
 - 9.Simple 
 
  
step2 run demo
对Spring Cache有了一个大概的了解后,我们首先使用起来,跑个demo。 
定义一个用户查询方法 
- @Component 
 - public class CacheSample { 
 -     @Cacheable(cacheNames = "users") 
 -     public Map<Long, User> getUser(final Collection<Long> userIds) { 
 -         System.out.println("not cache"); 
 -         final Map<Long, User> mapUser = new HashMap<>(); 
 -         userIds.forEach(userId -> { 
 -             mapUser.put(userId, User.builder().userId(userId).name("name").build()); 
 -         }); 
 -         return mapUser; 
 -     } 
 
  
配置一个CacheManager 
- @Configuration 
 - public class CacheConfig { 
 -     @Primary 
 -     @Bean(name = { "cacheManager" }) 
 -     public CacheManager getCache() { 
 -       return new ConcurrentMapCacheManager("users"); 
 -     } 
 
  
API调用 
- @RestController 
 - @RequestMapping("/api/cache") 
 - public class CacheController { 
 -     @Autowired 
 -     private CacheSample cacheSample; 
 -     @GetMapping("/user/v1/1") 
 -     public List<User> getUser() { 
 -         return cacheSample.getUser(Arrays.asList(1L,2L)).values().stream().collect(Collectors.toList()); 
 -     } 
 -     } 
 
  
step3 debug 查看实现
                        (编辑:52站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |