加入收藏 | 设为首页 | 会员中心 | 我要投稿 河北网 (https://www.hebeiwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

怎样举办高效的源码阅读:以Spring Cache扩展为例带你搞清晰

发布时间:2019-08-02 01:40:35 所属栏目:建站 来源:三旬老汉
导读:择要 一般开拓中,必要用到各类百般的框架来实现API、体系的构建。作为措施员,除了会行使框架还必必要相识框架事变的道理。这样可以便于我们排盘查题,和自界说的扩展。那么怎样去进修框架呢。凡是我们通过阅读文档、查察源码,然后又很快健忘。始终不能
副问题[/!--empirenews.page--]

择要

一般开拓中,必要用到各类百般的框架来实现API、体系的构建。作为措施员,除了会行使框架还必必要相识框架事变的道理。这样可以便于我们排盘查题,和自界说的扩展。那么怎样去进修框架呢。凡是我们通过阅读文档、查察源码,然后又很快健忘。始终不能融汇意会。本文首要基于Spring Cache扩展为例,先容怎样举办高效的源码阅读。

SpringCache的先容

为什么以Spring Cache为例呢,缘故起因有两个

  1. Spring框架是web开拓最常用的框架,值得开拓者去阅读代码,接收头脑
  2. 缓存是企业级应用开拓必不行少的,而跟着体系的迭代,我们也许会必要用到内存缓存、漫衍式缓存。那么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。当必要提供接口给外部挪用,起首本身内部的实现也必需基于同样一套抽象机制

  1. 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,会凭证指定的次序去实现

  1. 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): 
  2. 1.Generic 
  3. 2.JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others) 
  4. 3.EhCache 2.x 
  5. 4.Hazelcast 
  6. 5.Infinispan 
  7. 6.Couchbase 
  8. 7.Redis 
  9. 8.Caffeine 
  10. 9.Simple 

step2 run demo

对Spring Cache有了一个或许的相识后,我们起首行使起来,跑个demo。

界说一个用户查询要领

  1. @Component 
  2. public class CacheSample { 
  3.     @Cacheable(cacheNames = "users") 
  4.     public Map<Long, User> getUser(final Collection<Long> userIds) { 
  5.         System.out.println("not cache"); 
  6.         final Map<Long, User> mapUser = new HashMap<>(); 
  7.         userIds.forEach(userId -> { 
  8.             mapUser.put(userId, User.builder().userId(userId).name("name").build()); 
  9.         }); 
  10.         return mapUser; 
  11.     } 

设置一个CacheManager

  1. @Configuration 
  2. public class CacheConfig { 
  3.     @Primary 
  4.     @Bean(name = { "cacheManager" }) 
  5.     public CacheManager getCache() { 
  6.       return new ConcurrentMapCacheManager("users"); 
  7.     } 

API挪用

  1. @RestController 
  2. @RequestMapping("/api/cache") 
  3. public class CacheController { 
  4.     @Autowired 
  5.     private CacheSample cacheSample; 
  6.     @GetMapping("/user/v1/1") 
  7.     public List<User> getUser() { 
  8.         return cacheSample.getUser(Arrays.asList(1L,2L)).values().stream().collect(Collectors.toList()); 
  9.     } 
  10.     } 

step3 debug 查察实现

(编辑:河北网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读