本指南逐步介绍了使用Apache Geode的数据管理系统来缓存来自应用程序代码的某些调用的过程。
| 有关Apache Geode概念的更多常识以及如何从Apache Geode访问数据,请通读指南“使用Apache Geode访问数据”。 |
你会建立什么
您将构建一个服务,该服务从CloudFoundry托管的Quote服务请求报价,并将其缓存在Apache Geode中。
然后,您将看到再次获取相同的报价将消除对Quote服务的昂贵调用,因为在给定相同请求的情况下,由Apache Geode支持的Spring Cache Abstraction将用于缓存结果。
报价服务位于...
http://gturnquist-quoters.cfapps.io
Quote服务具有以下API ...
GET / api-获取所有报价
GET / api / random-获取随机报价
GET / api / {id}-获取具体报价
你需要什么
-
约15分钟
-
最喜欢的文本编辑器或IDE
-
JDK 1.8或更高版本
-
您还可以将代码直接导入到IDE中:
如何完成本指南
像大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都可以使用代码。
要从头开始,请继续进行“从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提供了一种快速的方法来提取应用程序所需的所有依赖关系,并为您完成了许多设置。本示例需要“ Spring for Apache Geode ”依赖项。
以下清单显示了pom.xml使用Maven时的示例文件:
<?xml版本=“ 1.0”编码=“ 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>
<父母>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-parent </ artifactId>
<version> 2.4.1 </ version>
</ parent>
<groupId> org.springframework </ groupId>
<artifactId> gs-caching-gemfire </ artifactId>
<version> 0.1.0 </ version>
<属性>
<spring-shell.version> 1.2.0.RELEASE </spring-shell.version>
</ properties>
<依赖项>
<依赖性>
<groupId> javax.cache </ groupId>
<artifactId> cache-api </ artifactId>
<scope>运行时</ scope>
</ dependency>
<依赖性>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter </ artifactId>
</ dependency>
<依赖性>
<groupId> org.springframework.data </ groupId>
<artifactId> spring-data-geode </ artifactId>
</ dependency>
<依赖性>
<groupId> com.fasterxml.jackson.core </ groupId>
<artifactId> jackson-databind </ artifactId>
</ dependency>
<依赖性>
<groupId> org.projectlombok </ groupId>
<artifactId>龙目岛</ artifactId>
</ dependency>
<依赖性>
<groupId> org.springframework.shell </ groupId>
<artifactId>弹簧壳</ artifactId>
<version> $ {spring-shell.version} </ version>
<scope>运行时</ scope>
</ dependency>
</ dependencies>
<内部版本>
<插件>
<插件>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-maven-plugin </ artifactId>
</ plugin>
</ plugins>
</ build>
</ project>
以下清单显示了build.gradle使用Gradle时的示例文件:
插件{
id'org.springframework.boot'版本'2.4.1'
id'io.spring.dependency-management'版本'1.0.8.RELEASE'
id“ io.freefair.lombok”版本“ 5.3.0”
id'java'
}
套用外挂程式:'eclipse'
套用外挂程式:'idea'
组=“ org.springframework”
版本=“ 0.1.0”
sourceCompatibility = 1.8
targetCompatibility = 1.8
储存库{
mavenCentral()
}
依赖项{
实现“ org.springframework.boot:spring-boot-starter”
实现“ org.springframework.data:spring-data-geode”
实现“ com.fasterxml.jackson.core:jackson-databind”
实现“ 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通过使用Lombok项目,简化了该类的实现。
除了Quote,还QuoteResponse捕获由报价请求中发送的报价服务发送的响应的整个有效负载。它包括请求的status(aka 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使用Spring的 RestTemplate查询报价服务的API。Quote服务返回一个JSON对象,但是Spring使用Jackson将数据绑定到QuoteResponse一个Quote对象,并最终绑定到一个对象。
该服务类的关键是如何requestQuote用注释@Cacheable("Quotes")。Spring的Caching Abstraction拦截对的调用,requestQuote以检查服务方法是否已被调用。如果是这样,Spring的缓存抽象只会返回缓存的副本。否则,Spring继续调用该方法,将响应存储在缓存中,然后将结果返回给调用方。
我们还在服务方法@CachePut上使用了注释requestRandomQuote。由于此服务方法调用返回的报价是随机的,因此我们不知道会收到哪个报价。因此,我们不能Quotes在调用之前查询缓存(即),但可以缓存调用的结果,这将对后续requestQuote(id)调用产生积极影响,前提是先前随机选择了感兴趣的报价并对其进行了缓存。
,@CachePut使用SpEL表达式(“#result.id”)访问服务方法调用的结果,并检索的IDQuote用作缓存键。您可以在此处了解有关Spring的Cache Abstraction SpEL上下文的更多信息。
| 您必须提供缓存的名称。出于演示目的,我们将其命名为“ Quotes”,但在生产中,建议选择适当的描述性名称。这也意味着可以将不同的方法与不同的缓存关联。如果您对每个缓存有不同的配置设置,例如不同的到期或逐出策略等,这将很有用。 |
稍后,当您运行代码时,您将看到运行每个调用所花费的时间,并且能够辨别缓存对服务响应时间的影响。这证明了缓存某些调用的价值。如果您的应用程序不断查找相同的数据,则缓存结果可以显着提高性能。
使应用程序可执行
尽管Apache Geode缓存可以嵌入到Web应用程序和WAR文件中,但是下面演示的更简单的方法创建了一个独立的应用程序。您可以将所有内容打包到一个可执行的JAR文件中,该文件由一个好的旧Javamain()方法驱动。
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 Boot根据类路径设置,其他bean和各种属性设置开始添加bean。例如,如果spring-webmvc在类路径上,则此注释将应用程序标记为Web应用程序并激活关键行为,例如设置DispatcherServlet。 -
@ComponentScan:告诉Spring在包中寻找其他组件,配置和服务hello,让它找到控制器。
该main()方法使用Spring Boot的SpringApplication.run()方法来启动应用程序。您是否注意到没有一行XML?也没有web.xml文件。该Web应用程序是100%纯Java,因此您无需处理任何管道或基础结构。
配置的顶部是一个重要的注释:@EnableGemfireCaching。这将启用缓存(即使用Spring的 @EnableCaching注释进行元注释),并在后台声明其他重要的bean,以支持使用Apache Geode作为缓存提供程序的缓存。
第一个bean是QuoteService用于访问Quotes REST-ful Web服务的实例。
其他两个需要缓存引号并执行应用程序的操作。
-
quotesRegionLOCAL在缓存内定义一个Apache Geode客户区域来存储报价。它专门命名为“ Quotes”以匹配@Cacheable("Quotes")我们QuoteService方法上的用法。 -
runner是用于运行我们的应用程序的Spring BootApplicationRunner接口的实例。
第一次请求报价(使用requestQuote(id))时,会发生高速缓存未命中,并且将调用服务方法,从而导致明显的延迟,在接近零毫秒的位置上没有延迟。在这种情况下,缓存由id服务方法的输入参数(即)链接requestQuote。换句话说,id方法参数是缓存键。随后请求由ID标识的相同报价将导致缓存命中,从而避免了昂贵的服务调用。
出于演示目的,对的调用QuoteService被包装在一个单独的方法(requestQuote在Application类内部)中,以捕获进行服务调用的时间。这样一来,您就可以准确地看到任何一个请求花费的时间。
建立可执行的JAR
您可以使用Gradle或Maven从命令行运行该应用程序。您还可以构建一个包含所有必需的依赖项,类和资源的可执行JAR文件,然后运行该文件。生成可执行jar使得在整个开发生命周期中,跨不同环境等等的情况下,都可以轻松地将服务作为应用程序进行发布,版本控制和部署。
如果您使用Gradle,则可以使用来运行该应用程序./gradlew bootRun。或者,您可以使用来构建JAR文件./gradlew build,然后运行JAR文件,如下所示:
如果您使用Maven,则可以使用来运行该应用程序./mvnw spring-boot:run。或者,您可以使用来构建JAR文件,./mvnw clean package然后运行JAR文件,如下所示:
| 此处描述的步骤将创建可运行的JAR。您还可以构建经典的WAR文件。 |
显示日志记录输出。该服务应在几秒钟内启动并运行。
“带有@springframework的@springboot是纯粹的生产力!谁在#java中说过必须编写比其他langs多一倍的代码?#newFavLib” 高速缓存未命中[true]-经过的时间[776 ms] “带有@springframework的@springboot是纯粹的生产力!谁在#java中说过必须编写比其他langs多一倍的代码?#newFavLib” 高速缓存未命中[false]-经过的时间[0 ms] “真正喜欢Spring Boot,使独立的Spring应用程序变得容易。” 高速缓存未命中[true]-经过的时间[96 ms]
从中可以看到,对报价服务的第一次调用花费了776毫秒,并导致缓存未命中。但是,第二个请求相同报价的调用花费了0毫秒,并导致了缓存命中。这清楚地表明第二个呼叫已缓存,并且从未真正到达Quote服务。但是,当对特定的非缓存报价请求进行最终服务调用时,该过程花费了96毫秒,并导致缓存未命中,因为在调用之前,此新报价先前不在缓存中。
概括
恭喜你!您刚刚构建了执行一项昂贵操作的服务,并对其进行了标记,以便可以缓存结果。
也可以看看
以下指南也可能会有所帮助:
是否要编写新指南或为现有指南做出贡献?查看我们的贡献准则。
| 所有指南均以代码的ASLv2许可证和写作的Attribution,NoDerivatives创用CC许可证发布。 |