Spring认证指南:了解如何在 GemFire 中缓存数据

开发 前端
本指南演练了使用阿帕奇大地的数据管理系统,用于缓存应用程序代码中的某些调用。

本指南演练了使用阿帕奇大地的数据管理系统,用于缓存应用程序代码中的某些调用。

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

您将构建的内容

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

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

报价服务位于:

https://quoters.apps.pcfone.io。

报价服务具有以下 API:

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

您将需要什么

  1. 约15分钟。
  2. 喜欢的文本编辑器或 IDE。
  3. JDK 1.8或更高版本。
  4. 格拉德尔 4+或梅文 3.2+。
  5. 您还可以将代码直接导入到 IDE 中:
  • 弹簧工具套件 (STS)。
  • IntelliJ IDEA。

如何完成本指南

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

要从头开始,请转到从 Spring Initializr 开始。

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

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

完成后,您可以根据 中的代码检查结果。

gs-caching-gemfire/complete。

从 Spring Initializr 开始

对于所有Spring应用程序,您应该从Spring Initializr.Spring Initializr提供了一种快速的方法来提取应用程序所需的所有依赖项,并为您完成许多设置。此示例需要"Apache Geode 的 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.5.6</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.5.6'
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();
}
}COPY

域类具有 和 属性。这些是您将在本指南中进一步收集的两个主要属性。通过使用QuoteidquoteQuote龙目岛项目。

此外,还会捕获报价服务在报价请求中发送的响应的整个有效负载。它包括请求的(又名 )以及 .此类还使用

QuoteQuoteResponsestatustypequote龙目岛项目以简化实现。

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

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

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

这两个类都标有 。这意味着即使可以检索其他 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);
}
}COPY

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

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

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

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

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

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

使应用程序可执行

尽管 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;
}
}COPY

@SpringBootApplication是添加以下所有内容的便利注释:

  • @Configuration:将类标记为应用程序上下文的 Bean 定义的源。
  • @EnableAutoConfiguration:告诉 Spring Boot 根据类路径设置、其他 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 Boot 接口的一个实例。ApplicationRunner。

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

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

QuoteServicerequestQuoteApplication。

构建可执行的 JAR

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

如果您使用 Gradle,则可以使用 运行应用程序。或者,您可以使用 JAR 文件构建 JAR 文件,然后运行该 JAR 文件,如下所示:./gradlew bootRun./gradlew build。

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

如果使用 Maven,则可以使用 运行应用程序。或者,您可以使用 JAR 文件构建 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 毫秒并导致缓存未命中,因为在调用之前,此新报价之前不在缓存中。

总结

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

责任编辑:姜华 来源: 今日头条
相关推荐

2022-02-11 08:54:33

SpringWeb 应用执行表单

2020-05-25 07:00:00

双因素认证身份认证密码

2022-02-15 08:22:28

Neo4jSpring数据库

2022-03-01 14:55:39

数据库Spring批处理

2016-08-29 21:36:55

nginxWeb缓存

2022-06-28 15:04:32

容器Docker

2022-06-28 15:06:35

容器Spring

2022-06-28 07:03:59

架构认证安全

2019-07-26 15:10:49

Windows 10屏幕缓存Windows

2022-04-27 08:55:01

Spring外部化配置

2022-12-01 15:34:26

Arch LinuxOpenOffice

2015-12-14 17:35:21

GemFire12306分布式

2011-03-21 12:41:41

JavaScript

2018-10-08 09:35:59

2009-01-30 09:12:11

SpringApplicationJavaWeb

2011-04-06 13:40:48

Delphi

2010-08-10 15:02:18

Oracle认证数据库

2021-01-30 17:57:23

Python缓存开发

2015-07-29 14:51:11

身份验证PeriscopeGoogle认证绕过

2023-11-03 12:52:00

缓存系统设计
点赞
收藏

51CTO技术栈公众号