3年前 (2021-04-17)  相关技术 |   抢沙发  2227 
文章评分 0 次,平均分 0.0

SpringBoot集成Caffeine缓存
在SpringBoot的这篇文章中,我们将研究如何将SpringBoot与缓存集成。我们将检查springboot自动配置特性,它能够透明地挂接缓存。

Caffeine缓存

Caffeine是一个基于java8的高性能缓存库,提供接近最佳的命中率。它提供了一个非常类似于google guavaapi的内存缓存。如果caffinecachemanager在类路径中找到Caffeine,Spring引导缓存启动器会自动配置caffinecachemanager。Spring框架支持透明地向应用程序添加缓存。让我们看看如何将SpringBoot与缓存集成。

Maven依赖项

为了支持SpringBoot,我们需要在SpringBoot应用程序中添加以下两个依赖项。

  • Spring Boot caching stater.
  • Caffeine cache provider.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.7.0</version>
</dependency>

有关最新版本,请访问Caffeine网站。

服务设置

让我们创建一个简单的客户服务,它将从底层系统返回客户信息。我们将使用caffinecache在这个层上添加Spring框架缓存抽象。让我们看看我们的服务类:

public interface CustomerService {
    Customer getCustomer(final Long customerID);
}
// Implementation
@Service
@CacheConfig(cacheNames = {"customer"})
public class DefaultCustomerService implements CustomerService {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultCustomerService.class);

    @Cacheable
    @Override
    public Customer getCustomer(Long customerID) {
        LOG.info("Trying to get customer information for id {} ",customerID);
        return getCustomerData(customerID);
    }

    private Customer getCustomerData(final Long id){
        Customer customer = new Customer(id, "testemail@test.com", "Test Customer");
        return  customer;
    }
}

有几个重要的要点要讨论:

  • @CacheConfig是类级注释,有助于简化缓存配置。
  • 用于标定可缓存方法的@Cacheable注释。简单地说,这个注释用于显示缓存API,我们希望将此方法的结果存储到缓存中,因此,在后续调用时,在缓存中返回的值不执行方法。

Spring缓存提供了一种非常透明的方式来启用缓存。我们在代码库中没有使用Caffeine cache的直接依赖,所有这些都是由Spring缓存框架内部处理的。

Caffeine Cache配置

SpringBoot提供了几个选项,可以在启动时配置Caffeine Cache缓存。我们可以通过配置文件配置这些属性(application.propertiesapplication.yml)或以编程方式。让我们看看如何使用应用程序属性文件:

spring.cache.cache-names=ccustomer
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

这个spring.cache.cache-names创建客户缓存。Caffeine规范将缓存的最大大小定义为500,生存时间为10分钟。

Caffeine Java配置

我们还可以使用Java配置配置缓存。让我们看看Java配置是什么样子的:

@Configuration
public class CaffeineCacheConfig {

 @Bean
 public CacheManager cacheManager() {
  CaffeineCacheManager cacheManager = new CaffeineCacheManager("customer");
  cacheManager.setCaffeine(caffeineCacheBuilder());
  return cacheManager;
 }

 Caffeine < Object, Object > caffeineCacheBuilder() {
  return Caffeine.newBuilder()
   .initialCapacity(100)
   .maximumSize(500)
   .expireAfterAccess(10, TimeUnit.MINUTES)
   .weakKeys()
   .recordStats();
 }
}

运行应用程序

让我们运行应用程序来查看它的实际运行情况:

@Component
public class CaffeineCacheApp implements CommandLineRunner {

 private static final Logger LOG = LoggerFactory.getLogger(CaffeineCacheApp.class);

 @Autowired
 CustomerService customerService;

 @Override
 public void run(String...args) throws Exception {

  LOG.info("Starting the Caffine cache testing process");
  customerService.getCustomer(1 l); //No hit , since this is the first request.
  customerService.getCustomer(2 l); //No hit , since this is the first request.
  customerService.getCustomer(1 l); //hit , since it is already in the cache.
  customerService.getCustomer(1 l); //hit , since it is already in the cache.
  customerService.getCustomer(1 l); //hit , since it is already in the cache.
  customerService.getCustomer(1 l); //hit , since it is already in the cache.
 }
}

如果您查看上述程序的输出,它是这样的:

2019-05-15 20:09:50.865  INFO 86848 --- [           main] com.javadevjournal.CaffeineCacheApp      : Starting the Caffeine cache testing process
2019-05-15 20:09:50.879  INFO 86848 --- [           main] c.j.service.impl.DefaultCustomerService  : Trying to get customer information for id 1 
2019-05-15 20:09:50.882  INFO 86848 --- [           main] c.j.service.impl.DefaultCustomerService  : Trying to get customer information for id 2

一旦客户数据在缓存中,它就为缓存中的所有后续调用提供服务。看一下日志,虽然我们调用了getCustomer(1),但是日志语句只打印了一次,因为所有后续调用都是从缓存中得到服务的。

小结

在本文中,我们看到了如何将SpringBoot与缓存集成。我们选中了使用配置文件或通过Java配置来配置Caffeine的选项。本文的源代码可以在GitHub上找到:

https://github.com/umeshawasthi/javadevjournal/tree/master/Spring-Boot/spring-boot-caffeine-application

 

除特别注明外,本站所有文章均为老K的Java博客原创,转载请注明出处来自https://javakk.com/1829.html

关于

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册