SpringBoot 2 缓存数据至 Pivotal GemFire

开篇词

该指南将逐步介绍使用 Pivotal GemFire 的数据结构来缓存代码中的某些调用。

有关 Pivotal GemFire 概念和从 Pivotal GemFire 访问数据的更多常规知识,请通读使用 Pivotal GemFire 访问数据的指南。

你将创建的应用

我们将构建一个服务,该服务从 CloudFoundry 托管的引句服务请求引句,并将其缓存在 Pivotal GemFire 中。

然后,我们将看到再次获取相同引句将消除对引句服务的昂贵调用,因为在相同的请求下,由 Pivotal GemFire 支持的 Spring Cache Abstraction 将用于缓存结果。

引句服务位于…

http://gturnquist-quoters.cfapps.io

引句服务所提供的 API…

GET /api         - get all quotes
GET /api/random  - get random quote
GET /api/{id}    - get specific quote

你将需要的工具

如何完成这个指南

像大多数的 Spring 入门指南一样,你可以从头开始并完成每个步骤,也可以绕过你已经熟悉的基本设置步骤。如论哪种方式,你最终都有可以工作的代码。

待一切就绪后,可以检查一下 gs-caching-gemfire/complete 目录中的代码。
 

用 Gradle 来构建

首先,我们设置一个基本的构建脚本。在使用 Spring 构建应用时可以使用任何喜欢的构建系统,但此处包含使用 GradleMaven 所需的代码。如果你都不熟悉,请参阅使用 Gradle 构建 Java 项目使用 Maven 构建 Java 项目

创建目录结构

在我们选择的项目目录中,创建以下自目录结构;例如,在 *nix 系统上使用 mkdir -p src/main/java/hello

└── src
    └── main
        └── java
            └── hello

创建 Gradle 构建文件

以下是初始 Gradle 构建文件。
build.gradle

buildscript {
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/libs-release" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.2.1.RELEASE")
    }
}

plugins {
    id "io.spring.dependency-management" version "1.0.5.RELEASE"
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 1.8
targetCompatibility = 1.8

bootJar {
    baseName = 'gs-caching-gemfire'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/libs-release" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude group: "org.springframework.boot", module: "spring-boot-starter-logging"
    }
    compile("org.springframework.data:spring-data-gemfire")
    compile("com.fasterxml.jackson.core:jackson-databind")
    compile("org.projectlombok:lombok")
    runtime("javax.cache:cache-api")
    runtime("org.springframework.shell:spring-shell:1.2.0.RELEASE")
}

Spring Boot gradle 插件提供了许多方便的功能:

  • 它收集类路径上的所有 jar,并构建一个可运行的单个超级 jar,这使执行和传输服务更加方便;
  • 它搜索 public static void main() 方法并将其标记为可运行类;
  • 它提供了一个内置的依赖解析器,用于设置版本号以及匹配 Spring Boot 依赖。我们可以覆盖所需的任何版本,但默认为 Boot 选择的一组版本。
     

用 Maven 来构建

首先,我们搭建一个基本的构建脚本。使用 Spring 构建应用时,可以使用任何喜欢的构建系统,但是此处包含了使用 Maven 所需的代码。如果你不熟悉 Maven,请参阅使用 Maven 构建 Java 项目

创建目录结构

在我们选择的项目目录中,创建以下自目录结构;例如,在 *nix 系统上使用 mkdir -p src/main/java/hello

└── src
    └── main
        └── java
            └── hello

创建 Maven 构建文件

以下是初始 Maven 构建文件。
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>

    <groupId>org.springframework</groupId>
    <artifactId>gs-caching-gemfire</artifactId>
    <version>0.1.0</version>

    <properties>
        <spring-shell.version>1.2.0.RELEASE</spring-shell.version>
    </properties>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-gemfire</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.shell</groupId>
            <artifactId>spring-shell</artifactId>
            <version>${spring-shell.version}</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Spring Boot Maven 插件提供了许多方便的功能:

  • 它收集类路径上的所有 jar,并构建一个可运行的单个超级 jar,这使执行和传输服务更加方便;
  • 它搜索 public static void main() 方法并将其标记为可运行类;
  • 它提供了一个内置的依赖解析器,用于设置版本号以及匹配 Spring Boot 依赖。我们可以覆盖所需的任何版本,但默认为 Boot 选择的一组版本。
     

用 IDE 来构建

为获取的数据创建可绑定对象

现在,我们已经搭建了项目和构建系统,我们可以集中精力定义域对象,以捕获从 Quote 服务中获取引句(数据)所需的位。

src/main/java/hello/Quote.java

package hello;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import org.springframework.util.ObjectUtils;

import lombok.Data;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@SuppressWarnings("unused")
public class Quote {

  private Long id;

  private String quote;

  @Override
  public boolean equals(Object obj) {

    if (this == obj) {
      return true;
    }

    if (!(obj instanceof Quote)) {
      return false;
    }

    Quote that = (Quote) obj;

    return ObjectUtils.nullSafeEquals(this.getId(), that.getId());
  }

  @Override
  public int hashCode() {

    int hashValue = 17;

    hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getId());

    return hashValue;
  }

  @Override
  public String toString() {
    return getQuote();
  }
}

Quote 域类具有 idquote 属性。这是我们将在该指南中进一步了解的两个主要属性。Quote 类的实现已经通过使用 Project Lombok 得以简化。

除了 Quote 之外,QuoteResponse 捕获在 Quote 请求中发送的 Quote 服务所发送的响应的整个有效负载。它包括请求的 status(也即 type)及 quote。该类还使用 Project Lombok 简化了实现。

src/main/java/hello/QuoteResponse.java

package hello;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class QuoteResponse {

  @JsonProperty("value")
  private Quote quote;

  @JsonProperty("type")
  private String status;

  @Override
  public String toString() {
    return String.format("{ @type = %1$s, quote = '%2$s', status = %3$s }",
      getClass().getName(), getQuote(), getStatus());
  }
}

Quote 服务的典型响应如下所示:

{
  "type":"success",
  "value": {
    "id":1,
    "quote":"Working with Spring Boot is like pair-programming with the Spring developers."
  }
}

这两个类都标有 @JsonIgnoreProperties(ignoreUnknown=true)。这意味着即使其他 JSON 属性可被检索,其也将被忽略。
 

引句服务查询查询数据

下一步是创建一个查询引句的服务类。

src/main/java/hello/QuoteService.java

package hello;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;

import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@SuppressWarnings("unused")
@Service
public class QuoteService {

  protected static final String ID_BASED_QUOTE_SERVICE_URL = "http://gturnquist-quoters.cfapps.io/api/{id}";
  protected static final String RANDOM_QUOTE_SERVICE_URL = "http://gturnquist-quoters.cfapps.io/api/random";

  private volatile boolean cacheMiss = false;

  private final RestTemplate quoteServiceTemplate = new RestTemplate();

  /**
   * Determines whether the previous service method invocation resulted in a cache miss.
   *
   * @return a boolean value indicating whether the previous service method invocation resulted in a cache miss.
   */
  public boolean isCacheMiss() {
    boolean cacheMiss = this.cacheMiss;
    this.cacheMiss = false;
    return cacheMiss;
  }

  protected void setCacheMiss() {
    this.cacheMiss = true;
  }

  /**
   * Requests a quote with the given identifier.
   *
   * @param id the identifier of the {@link Quote} to request.
   * @return a {@link Quote} with the given ID.
   */
  @Cacheable("Quotes")
  public Quote requestQuote(Long id) {
    setCacheMiss();
    return requestQuote(ID_BASED_QUOTE_SERVICE_URL, Collections.singletonMap("id", id));
  }

  /**
   * Requests a random quote.
   *
   * @return a random {@link Quote}.
   */
  @CachePut(cacheNames = "Quotes", key = "#result.id")
  public Quote requestRandomQuote() {
    setCacheMiss();
    return requestQuote(RANDOM_QUOTE_SERVICE_URL);
  }

  protected Quote requestQuote(String URL) {
    return requestQuote(URL, Collections.emptyMap());
  }

  protected Quote requestQuote(String URL, Map<String, Object> urlVariables) {

    return Optional.ofNullable(this.quoteServiceTemplate.getForObject(URL, QuoteResponse.class, urlVariables))
      .map(QuoteResponse::getQuote)
      .orElse(null);
  }
}

QuoteService 使用 SpringRestTemplate 查询 Quote 服务的 API。Quote 服务返回一个 JSON 对象,但是 Spring 使用 Jackson 将数据绑定至 QuoteResponse 并最终绑定到 Quote 对象。

该服务类的关键所在是如何使用 @Cacheable("Quotes") 来标注 requestQuoteSpring 的缓存抽象拦截了对 requestQuote 的调用,以检查是否已经调用了 service 方法。如果是这样,Spring 的缓存抽象只会返回缓存的副本。否则,Spring 继续调用该方法,将响应存储在缓存中,然后将结果返回给调用方。

我们还在 requestRandomQuote 服务方法上使用了 @CachePut 注解。由于该服务方法调用返回的引句是随机的,因此我们不知道会收到哪个引句。因此,我们不能在调用之前查询缓存(即 Quotes),但是我们可以缓存该调用的结果,这将对后续的 requestQuote(id) 调用产生积极的影响,假设感兴趣的引句是先前随机选择并缓存的。

@CachePut 使用 SpEL 表达式("#result.id")访问服务方法调用的结果,并检索 Quote 的 ID 以用作缓存键。我们可以在该处了解有关 Spring 的 Cache Abstraction SpEL 上下文的更多信息。

我们必须提供缓存的名称。处于演示目的,我们将其命名为 “Quotes”,但在生产中,建议选择适当的描述性名称。这也意味着可以将不同的方法与不同的缓存关联。如果我们为每个缓存使用不同的配置设置(例如不同的到期或回收策略等等),这将很有用。

稍后,当我们运行代码时,我们将看到运行每个调用所花费的时间,并且能够辨别缓存对服务响应时间的影响。这证明了缓存某些调用的价值。如果我们的应用不断查找相同的数据,则缓存结果可以显著提高性能。
 

使应用可执行

尽管 Pivotal GemFire 缓存可以嵌入到 Web 应用和 WAR 文件中,但是下面演示的更简单的方法创建了一个独立的应用。我们将所有内容打包在一个可执行的 JAR 文件中,该文件由一个好而老的 Java main() 方法所驱动。

src/main/java/hello/Application.java

package hello;

import java.util.Optional;

import org.apache.geode.cache.client.ClientRegionShortcut;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.gemfire.cache.config.EnableGemfireCaching;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.config.annotation.EnableCachingDefinedRegions;

@SpringBootApplication
@ClientCacheApplication(name = "CachingGemFireApplication", logLevel = "error")
@EnableCachingDefinedRegions(clientRegionShortcut = ClientRegionShortcut.LOCAL)
@EnableGemfireCaching
@SuppressWarnings("unused")
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Bean
  ApplicationRunner runner(QuoteService quoteService) {

    return args -> {
      Quote quote = requestQuote(quoteService, 12L);
      requestQuote(quoteService, quote.getId());
      requestQuote(quoteService, 10L);
    };
  }

  private Quote requestQuote(QuoteService quoteService, Long id) {

    long startTime = System.currentTimeMillis();

    Quote quote = Optional.ofNullable(id)
      .map(quoteService::requestQuote)
      .orElseGet(quoteService::requestRandomQuote);

    long elapsedTime = System.currentTimeMillis();

    System.out.printf("\"%1$s\"%nCache Miss [%2$s] - Elapsed Time [%3$s ms]%n", quote,
      quoteService.isCacheMiss(), (elapsedTime - startTime));

    return quote;
  }
}

@SpringBootApplication 是一个便利的注解,它添加了以下所有内容:

  • @Configuration:将类标记为应用上下文 Bean 定义的源;
  • @EnableAutoConfiguration:告诉 Spring Boot 根据类路径配置、其他 bean 以及各种属性的配置来添加 bean。
  • @ComponentScan:告知 Spring 在 hello 包中寻找他组件、配置以及服务。

main() 方法使用 Spring Boot 的 SpringApplication.run() 方法启动应用。

配置的顶部是一个重要的注解:@EnableGemireCaching。这会启用缓存(即使用 Spring@EnableCaching 注解进行元注解),并在后台声明其它重要的 bean,以支持缓存并使用 Pivotal GemFire 作为缓存提供者。

第一个 bean 是 QuoteService 的实例,用于访问引句的 REST-ful Web 服务。

需要另外两个来缓存引句并执行应用的操作。

  • quotesRegion 在缓存内定义了一个 Pivotal GemFire LOCAL 客户区域来存储引句。它被指定命名为
    “Quotes”,以匹配 QuoteService 方法上 @Cacheable("Quotes") 的用法。
    runner 是用于运行我们的应用的 Spring Boot ApplicationRunner 接口的实例。

第一次请求引句(使用 requestQuote(id))时,会发生缓存未命中,并且将调用服务方法,从而导致明显的延迟,在接近零毫秒的位置没有延迟。在这种情况下,缓存是通过服务方法 requestQuote 的输入参数(例如 id)来进行链接的。换句话说,id 方法参数是缓存键。随后请求由 ID 标识的相同引句将导致缓存命中,从而避免了昂贵的服务调用。

出于演示目的,对 QuoteService 的调用被包装在一个单独的方法(Application 类中的 requestQuote)中,以捕获进行服务调用的时间。这样一来,我们就可以准确地看到任何一个请求花费的时间。

构建可执行 JAR

我们可以结合 Gradle 或 Maven 来从命令行运行该应用。我们还可以构建一个包含所有必须依赖项、类以及资源的可执行 JAR 文件,然后运行该文件。在整个开发生命周期中,跨环境等等情况下,构建可执行 JAR 可以轻松地将服务作为应用进行发布、版本化以及部署。

如果使用 Gradle,则可以借助 ./gradlew bootRun 来运行应用。或通过借助 ./gradlew build 来构建 JAR 文件,然后运行 JAR 文件,如下所示:

java -jar build/libs/gs-caching-gemfire-0.1.0.jar

如果使用 Maven,则可以借助 ./mvnw spring-boot:run 来运行该用。或可以借助 ./mvnw clean package 来构建 JAR 文件,然后运行 JAR 文件,如下所示:

java -jar target/gs-caching-gemfire-0.1.0.jar

我们还可以构建一个经典的 WAR 文件

显示日志记录输出。该服务应在几秒内启动并运行。

"@springboot with @springframework is pure productivity! Who said in #java one has to write double the code than in other langs? #newFavLib"
Cache Miss [true] - Elapsed Time [776 ms]
"@springboot with @springframework is pure productivity! Who said in #java one has to write double the code than in other langs? #newFavLib"
Cache Miss [false] - Elapsed Time [0 ms]
"Really loving Spring Boot, makes stand alone Spring apps easy."
Cache Miss [true] - Elapsed Time [96 ms]

从中可以看到,对引句服务的第一次调用花费了 776 毫秒,并导致了缓存未命中。但是,第二个请求相同引句的调用耗时 0 毫秒,并导致缓存命中。这清楚地表明第二个调用已被缓存,并且从未真正到达 Quote 服务。但是,当对特定的非缓存引句请求进行最终调用时,它花费了 96 毫秒,并且由于未在调用之前将该新引句提前存储在缓存中而导致缓存未命中。
 

概述

恭喜你!我们刚刚构建了一项执行昂贵操作的服务,并对其进行了标记,以便可以缓存结果。
 

参见

以下指南也可能会有所帮助:

想看指南的其他内容?请访问该指南的所属专栏:《Spring 官方指南

发布了132 篇原创文章 · 获赞 6 · 访问量 7942

猜你喜欢

转载自blog.csdn.net/stevenchen1989/article/details/104205656