阿拉丁和灯

Thoughts, stories and ideas.



利用Spring Cache API和Guava Cache实现来提升应用性能


在应用内enable本地缓存,就三步:

1. 在Application Config上enable caching

@Configuration
@EnableCaching
open class BizConfig {
}

2. 在需要cache的方法上,添加@Cacheable注解

public class DummyBookService implements BookService {

 @Override
 @Cacheable("book")
 public Book loadBook(String isbn) {
  // slow response time..
 }

 @Override
 @Cacheable("books")
 public List<Book> loadBookByAuthor(String author) {
  // Slow listing
 }
}

3. 提供cacheManager bean

@Bean
public CacheManager cacheManager() {
 SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
 GuavaCache cache1 = new GuavaCache("book", CacheBuilder.newBuilder().build());
 GuavaCache cache2 = new GuavaCache("books", CacheBuilder.newBuilder()
             .expireAfterAccess(30, TimeUnit.MINUTES)
             .build());
 simpleCacheManager.setCaches(Arrays.asList(cache1, cache2));
 return simpleCacheManager;
}

4. Trouble shooting

多个cacheManager的处理方法
https://stackoverflow.com/questions/38570211/how-to-have-multiple-cache-manager-configuration-in-spring-cache-java
接受多个参数的方法
https://stackoverflow.com/questions/14072380/cacheable-key-on-multiple-method-arguments

参考资料

https://dzone.com/articles/spring-caching-abstraction-and



View or Post Comments