在程序的入口中加入@ EnableCaching開啓緩存技術:html
@SpringBootApplication @EnableCaching public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
在須要緩存的地方加入@Cacheable註解,好比在getByIsbn()方法上加入@Cacheable(「books」),這個方法就開啓了緩存策略,當緩存有這個數據的時候,會直接返回數據,不會等待去查詢數據庫。數據庫
@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); } } }
這時再啓動程序,你會發現程序打印:緩存
isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’} 2017-04-23 18:17:09.479 INFO 8054 — [ main] forezp.AppRunner : isbn-4567 –>Book{isbn=’isbn-4567’, title=’Some book’} 2017-04-23 18:17:09.480 INFO 8054 — [ main] forezp.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’} 2017-04-23 18:17:09.480 INFO 8054 — [ main] forezp.AppRunner : isbn-4567 –>Book{isbn=’isbn-4567’, title=’Some book’} 2017-04-23 18:17:09.481 INFO 8054 — [ main] forezp.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’} 2017-04-23 18:17:09.481 INFO 8054 — [ main] forezp.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’}
只有打印前面2個數據,程序等了3s,以後的數據瞬間打印在控制檯上了,這說明緩存起了做用。ide
源碼來源this