首页 > 其他分享 >使用 Pivotal GemFire 缓存数据

使用 Pivotal GemFire 缓存数据

时间:2022-12-22 11:08:39浏览次数:33  
标签:缓存 Quote springframework 缓存数据 Pivotal GemFire import org id

使用 Pivotal GemFire 缓存数据_缓存

本指南将介绍使用Apache Geode的数据管理系统,用于缓存来自应用程序代码的某些调用。

有关 Apache Geode 概念和从 Apache Geode 访问数据的更多一般知识,请通读本指南,使用 Apache Geode 访问数据.

您将构建的内容

您将构建一个服务,该服务从CloudFoundry托管的报价服务请求报价,并将其缓存在Apache Geode中。

然后,您将看到再次获取相同的报价消除了对报价服务的昂贵调用,因为由Apache Geode支持的Spring缓存抽象将用于缓存结果,给定相同的请求。

报价服务位于...

https://quoters.apps.pcfone.io

报价服务具有以下 API...

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

你需要什么

  • 约15分钟
  • 最喜欢的文本编辑器或 IDE
  • JDK 1.8或以后
  • 格拉德尔 4+​或梅文 3.2+
  • 您也可以将代码直接导入到 IDE 中:
  • 弹簧工具套件 (STS)
  • 智能理念
  • VSCode

如何完成本指南

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

要从头开始,请继续从 Spring 初始化开始.

要跳过基础知识,请执行以下操作:

  • 下载​并解压缩本指南的源存储库,或使用吉特:git clone https://github.com/spring-guides/gs-caching-gemfire.git
  • 光盘成gs-caching-gemfire/initial
  • 跳转到创建用于获取数据的可绑定对象.

完成后,您可以根据 中的代码检查结果。​​gs-caching-gemfire/complete​

从 Spring 初始化开始

对于所有 Spring 应用程序,您应该从Spring Initializr.Spring Initializr 提供了一种快速的方式来提取应用程序所需的所有依赖项,并为您完成大量设置。此示例需要“Spring for Apache Geode”依赖项。

以下清单显示了使用 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.7.0</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>

<dependencies>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-geode</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>

以下清单显示了使用 Gradle 时的示例文件:​​build.gradle​

plugins {
id 'org.springframework.boot' version '2.7.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'io.freefair.lombok' version '6.3.0'
id 'java'
}

apply plugin: 'eclipse'
apply plugin: 'idea'

group = "org.springframework"
version = "0.1.0"
sourceCompatibility = '1.8'

repositories {
mavenCentral()
}

dependencies {
implementation "org.springframework.boot:spring-boot-starter"
implementation "org.springframework.data:spring-data-geode"
implementation "com.fasterxml.jackson.core:jackson-databind"
implementation "org.projectlombok:lombok"
runtimeOnly "javax.cache:cache-api"
runtimeOnly "org.springframework.shell:spring-shell:1.2.0.RELEASE"
}

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

设置项目和生成系统后,可以专注于定义捕获从 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​​​​id​​​​quote​​​​Quote​​龙目岛计划.

除了 之外,它还捕获报价请求中发送的报价服务发送的响应的全部有效负载。它包括请求的(也称为)以及 .此类还使用​​Quote​​​​QuoteResponse​​​​status​​​​type​​​​quote​​龙目岛计划以简化实施。

​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());
}
}

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

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

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

查询数据报价服务

下一步是创建查询报价的服务类。

​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 = "https://quoters.apps.pcfone.io/api/{id}";
protected static final String RANDOM_QUOTE_SERVICE_URL = "https://quoters.apps.pcfone.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);
}
}

使用 Spring 的来查询报价服务的​​QuoteService​​​​RestTemplate​​应用程序接口.Quote 服务返回一个 JSON 对象,但 Spring 使用 Jackson 将数据绑定到一个对象,并最终绑定到一个对象。​​QuoteResponse​​​​Quote​

此服务类的关键部分是如何使用 进行注释。​​requestQuote​​​​@Cacheable("Quotes")​春天的缓存抽象截获 to 的调用以检查是否已调用服务方法。如果是这样,Spring 的缓存抽象只是返回缓存的副本。否则,Spring 将继续调用该方法,将响应存储在缓存中,然后将结果返回给调用方。​​requestQuote​

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

使用 SpEL 表达式 (“#result.id”) 访问服务方法调用的结果,并检索要用作缓存键的 ID。你可以了解更多关于Spring的缓存抽象SpEL上下文的信息。​​@CachePut​​​​Quote​​这里.

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

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

使应用程序可执行

尽管 Apache Geode 缓存可以嵌入到 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")
@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 引导根据类路径设置、其他 bean 和各种属性设置开始添加 bean。例如,如果 在类路径上,则此注释会将应用程序标记为 Web 应用程序并激活关键行为,例如设置 .spring-webmvcDispatcherServlet
  • ​@ComponentScan​​:告诉 Spring 在包中查找其他组件、配置和服务,让它找到控制器。hello

该方法使用 Spring Boot 的方法启动应用程序。您是否注意到没有一行 XML?也没有文件。此 Web 应用程序是 100% 纯 Java,您无需处理配置任何管道或基础结构。​​main()​​​​SpringApplication.run()​​​​web.xml​

在配置的顶部是一个重要的注释:。这将打开缓存(即使用 Spring 的注释进行元注释),并在后台声明其他重要的 bean,以支持使用 Apache Geode 作为缓存提供程序缓存。​​@EnableGemfireCaching​​​​@EnableCaching​

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

另外两个是缓存报价和执行应用程序操作所必需的。

  • ​quotesRegion​​在缓存中定义一个 Apache Geode 客户端区域来存储报价。它被专门命名为“引号”,以匹配我们方法的用法。LOCAL@Cacheable("Quotes")QuoteService
  • ​runner​​是用于运行我们的应用程序的 Spring 引导接口的一个实例。ApplicationRunner

第一次请求报价(使用 )时,会发生缓存未命中,并且将调用服务方法,从而导致明显的延迟,该延迟不接近零毫秒。在这种情况下,缓存由服务方法的输入参数(即)链接。换句话说,方法参数是缓存键。对由 ID 标识的相同报价的后续请求将导致缓存命中,从而避免昂贵的服务调用。​​requestQuote(id)​​​​id​​​​requestQuote​​​​id​

出于演示目的,对 的调用包装在一个单独的方法(在类内部)中,以捕获进行服务调用的时间。这使您可以准确查看任何一个请求需要多长时间。​​QuoteService​​​​requestQuote​​​​Application​

构建可执行的 JAR

您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必需依赖项、类和资源的可执行 JAR 文件并运行该文件。通过构建可执行 jar,可以轻松地在整个开发生命周期中跨不同环境等将服务作为应用程序进行交付、版本控制和部署。

如果使用 Gradle,则可以使用 .或者,您可以使用 JAR 文件生成 JAR 文件,然后运行该文件,如下所示:​​./gradlew bootRun​​​​./gradlew build​

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

如果使用 Maven,则可以使用 运行应用程序。或者,您可以使用 JAR 文件生成 JAR 文件,然后运行该文件,如下所示:​​./mvnw spring-boot:run​​​​./mvnw clean package​

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

此处描述的步骤将创建一个可运行的 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 毫秒,并导致缓存命中。这清楚地表明第二个调用已缓存,并且从未真正命中报价服务。但是,当对特定的非缓存报价请求进行最终服务调用时,它花费了 96 毫秒并导致缓存未命中,因为此新报价在调用之前不在缓存中。

总结

祝贺!您刚刚构建了一个服务,该服务执行了昂贵的操作并对其进行了标记,以便缓存结果。

标签:缓存,Quote,springframework,缓存数据,Pivotal,GemFire,import,org,id
From: https://blog.51cto.com/u_15326439/5962392

相关文章