- 在线文档
- 项目结构
1.源码克隆:git clone https://github.com/spring-guides/gs-caching.git 2.包含两个项目initial和complete,initial可以根据文档练习完善,complete是完整项目 3.功能描述:构建应用程序,在图书存储库上启用缓存,获取同一本书的第二次和后续时间要快得多
-
源码分析
1.POM依赖 <dependencies> <!--https://blog.csdn.net/tongxin_tongmeng/article/details/128579882--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2.入口类 // https://blog.csdn.net/tongxin_tongmeng/article/details/128401278 @SpringBootApplication @EnableCaching public class CachingApplication { public static void main(String[] args) { SpringApplication.run(CachingApplication.class, args); } }
3.图书获取 @Component public class SimpleBookRepository implements BookRepository { @Override @Cacheable("books") public Book getByIsbn(String isbn) { simulateSlowService(); return new Book(isbn, "Some book"); } // Don't do this at home private void simulateSlowService() { try { long time = 3000L; Thread.sleep(time); } catch (InterruptedException e) { throw new IllegalStateException(e); } } }
4.测试类 @Component // https://blog.csdn.net/tongxin_tongmeng/article/details/128402169 public class AppRunner implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(AppRunner.class); private final BookRepository bookRepository; public AppRunner(BookRepository bookRepository) { this.bookRepository = bookRepository; } @Override public void run(String... args) throws Exception { logger.info(".... Fetching books"); logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234")); logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567")); logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234")); logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567")); logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234")); logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234")); } }
- 项目演示