Spring Data Pivotal Gemfire教程

1. Spring Data Pivotal Gemfire –简介

在这篇文章中,我们将介绍有关Spring Data Pivotal Gemfire的全面教程。 Pivotal Gemfire是由Apache Geode支持的内存中数据网格解决方案。 使用Pivotal Gemfire构建的应用程序使您可以在分布式服务器节点之间轻松扩展系统。 无论分布结构如何,Pivotal Gemfire均可确保数据一致性。 它使应用程序能够向数百万用户提供实时数据。
另一方面,Spring框架是一种广泛使用的框架,它为构建企业级应用程序提供了基础。 在本文中,我们将讨论Spring数据(Spring框架的众多模块之一)如何与Pivotal Gemfire集成,以加快开发过程并将Spring框架的功能引入Pivotal Gemfire应用程序。

2.本教程的先决条件

在进入本教程之前,有必要了解进行的假设以及继续进行本教程所需的工具。 在此,我假设您了解以下内容:

  • 了解访问关键数据
  • 对Spring框架的基本了解
  • 对Pivotal API调用的基本了解

在整个教程中,我们将使用以下工具和规范:

  • JDK 1.8
  • 弹簧工具套件/ IntelliJ
  • Maven的3.2+

3.开始

首先从项目开始,让我们创建一个Maven项目并添加以下依赖项。

pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.samples</groupId>
  <artifactId>pivotal_tutorial</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>


    <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</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>org.springframework.shell</groupId>
            <artifactId>spring-shell</artifactId>
            <version>${spring-shell.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

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

</project>

保存具有这些依赖项的项目,并允许其进行构建。 上面的文件包含必需的Spring Boot依赖关系以及Pivotal Gemfire的Spring Data依赖关系。 一旦项目下载了相关的依赖项,就可以继续编码部分。

带有Pivotal Gemfire的Spring Data帮助我们配置对分布式数据访问中心的访问。 这种结合可以帮助我们降低对磁盘的命中率,并使用内存中的缓存级别来维持更好的响应时间。 本教程将带您完成完整的设置和配置过程。

4.创建一个实体

首先,主要要求是创建一个实体。 让我们创建一个简单的Person实体,其中包含一个人的详细信息,例如人的姓名和年龄。 要创建这样的实体,请使用以下代码。

PersonEntity.java

package pivotal_tutorial;

import java.io.Serializable;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.gemfire.mapping.annotation.Region;

import lombok.Getter;

@Region(value = "People")
public class PersonEntity implements Serializable {

    @Id
    @Getter
    private final String name;

    @Getter
    private final int age;

    @PersistenceConstructor
    public PersonEntity(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	@Override
    public String toString() {
        return String.format("%s is %d years old", getName(), getAge());
    }
}

如您所见,有两个属性-名称和年龄,以及一个持久性构造函数。 在这里,请注意,该类已使用注释@Region进行注释。 此批注是枢轴指示符,用于指示框架使用特定名称存储此类的实例。 当它读取注释@Region("People") ,它将理解必须将PersonEntity的实例存储为People的名称。 带有注释@Id的字段将是实例的唯一键。

这里假设您了解Pivotal没有任何自动密钥生成系统。 因此,在实际进行数据持久化之前,您需要确保设置了id字段。

5.创建简单的查询

与Pivotal Gemfire框架结合的Spring Data就是关于存储和持久化数据的。 它着重于此管理对数据的访问。 此外,它还继承了Spring Data框架的强大功能,例如获得查询的功能。 框架的强大功能是您不再需要学习关键的gemfire查询语言。 您所需要做的就是编写一些Java代码段,该框架将在后端构建查询。
让我们从为上面显示的实体创建类似的片段开始。

PersonQueries.java

package pivotal_tutorial;
import org.springframework.data.gemfire.repository.query.annotation.Trace;
import org.springframework.data.repository.CrudRepository;

public interface PersonRepo extends CrudRepository<PersonEntity, String> {

    @Trace
    PersonEntity findByName(String name);

    @Trace
    Iterable findByAgeGreaterThan(int age);

    @Trace
    Iterable findByAgeLessThan(int age);

    @Trace
    Iterable findByAgeGreaterThanAndAgeLessThan(int greaterThanAge, int lessThanAge);
}

在上面的代码中,请注意,该类扩展了CrudRepository ,该类是Spring Data框架提供的类。 注释@Trace标识需要使用相关的函数来为后端运行的Pivotal Gemfire框架创建查询。 这些功能很容易理解。 下面提供了简要说明:

  • findByName :通过作为参数提供的name值查找实体
  • findByAgeGreaterThan :查找年龄大于提供的值的实体。 返回PersonEntity实例的可迭代列表。
  • findAgeLessThan :查找年龄小于提供的值的实体。 返回PersonEntity实例的可迭代列表。
  • findByAgeGreaterThanAndLessThan :查找年龄大于或小于提供的值的实体。 返回PersonEntity实例的可迭代列表。

6.创建一个应用程序

现在我们已经准备好查询和实体,让我们开始创建有助于数据事务的实际应用程序。 将创建具有视图的应用程序,以实例化实体并处理数据。 以下代码创建具有所有必要组件的应用程序。

App.java

package pivotal_tutorial;
import static java.util.Arrays.asList;
import static java.util.stream.StreamSupport.stream;

import java.io.IOException;

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.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.config.annotation.EnableEntityDefinedRegions;
import org.springframework.data.gemfire.repository.config.EnableGemfireRepositories;

@SpringBootApplication
@ClientCacheApplication(name = "AccessingDataGemFireApplication", logLevel = "error")
@EnableEntityDefinedRegions(basePackageClasses = PersonEntity.class,
  clientRegionShortcut = ClientRegionShortcut.LOCAL)
@EnableGemfireRepositories
public class App {

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

    @Bean
    ApplicationRunner run(PersonRepo personRepository) {

        return args -> {

            PersonEntity abk = new PersonEntity("Abhishek Kothari", 26);
            PersonEntity sumit = new PersonEntity("Sumit Punjabi", 25);
            PersonEntity john = new PersonEntity("John Doe", 34);

            System.out.println("Entering into accessing data from Pivotal GemFire framework");

            asList(abk, sumit, john).forEach(person -> System.out.println("\t" + person));

            System.out.println("Saving Alice, Bob and Carol to Pivotal GemFire...");

            personRepository.save(abk);
            personRepository.save(sumit);
            personRepository.save(john);

            System.out.println("Lookup each person by name...");

            asList(abk.getName(), sumit.getName(), john.getName())
              .forEach(name -> System.out.println("\t" + personRepository.findByName(name)));

            System.out.println("Query adults (over 18):");

            stream(personRepository.findByAgeGreaterThan(18).spliterator(), false)
              .forEach(person -> System.out.println("\t" + person));

            System.out.println("Query teens (less than 30):");

            stream(personRepository.findByAgeLessThan(30).spliterator(), false)
              .forEach(person -> System.out.println("\t" + person));

            System.out.println("Query teens (between 12 and 30):");

            stream(personRepository.findByAgeGreaterThanAndAgeLessThan(12, 30).spliterator(), false)
              .forEach(person -> System.out.println("\t" + person));
        };
    }
}

上面的类包含对已定义实体的所有可能的查询调用。 请注意,在该类中已注释了许多注释。 下面提供了每个注释的描述:

@SpringBootApplication :此批注指定该类将被视为Spring引导应用程序的起点。
@ClientCacheApplication :此注释指定应用程序应在后端使用由Spring Data支持的数据的客户端缓存。
@EnableDefinedRegions :注释用于指定需要使用并可用的实体。 该注释基本上完成了公开该类的相应实体的方法的任务。 @EnableGemfireRepositories :这是最重要的注释。 从名称本身可以清楚地看到注释的目的。 为了在Spring应用程序启动时启用gemfire存储库,此注释是必需的。 该注释将强制扫描当前包,以查找扩展Spring Data仓库类之一(例如PersonEntity

有时候,我们可能不希望将所有Spring Data实体公开到Gemfire框架中。 可以通过显式指定所需实体扩展的类来防止这种情况。 可以使用其属性basePackageClasses = TheRepository.class完成此操作
这里要注意的是,在区域定义中,我们指定了局部区域。 这对于Pivotal Gemfire很重要。 为了存储数据,Pivotal需要至少1个或更多区域。

7.缓存配置

Pivotal中可能有三种不同的缓存配置。 根据我们计划使用的区域,我们可以使用所需的批注之一使用Spring Data框架通过Pivotal Gemfire后端指定缓存和数据持久性。 以下是可以使用的三种可能的注释:

@ClientCacheApplication :将数据客户端缓存在本地存储中
@PeerCacheApplication :在同级之间缓存数据
@CacheServerApplication :在服务器端缓存数据

Pivotal Gemfire支持多种缓存拓扑,例如客户端/服务器,对等甚至WAN或LAN安排。 在客户端/服务器缓存拓扑中,客户端缓存查询的数据,而服务器缓存所有数据。 在对等拓扑中,即使网络中的设备也将缓存数据,以将其提供给最近的对等体。 对于WAN或LAN拓扑,如果您已连接到特定网络,则设备将缓存数据,并开始将数据分发给其他用户。 在上述情况下,我们使用了客户端缓存,因此一旦执行查询,缓存将完全在客户端完成。 出于相同的原因,我们指定了LOCAL区域。

我们将实体连接到名为People的区域。 这是使用注释Region指定的。 该注释是从Spring Data框架使用的。 稍后使用代码片段ClientRegionFactoryBean<String, PersonEntity>用于bean定义在应用程序层中映射此区域。 因此,我们注入了bean定义,并在People区域中定义了实例,否则,如果没有Spring Data框架,这是不可能的。

8.存放物件

在本指南中,您将创建三个本地Person对象,Abhishek,Sumit John。 最初,它们仅存在于内存中。 创建它们之后,您必须将它们保存到Pivotal GemFire。

现在,您运行几个查询。 第一个按名称查找所有人。 然后,您使用年龄属性执行少量查询以查找成人,婴儿和青少年。 打开日志记录后,您可以看到Spring Data for Pivotal GemFire代表您编写的查询。

9.执行代码并构建一个jar

现在,我们已经了解了代码的性能以及下一步的时间。 下一步是实际执行代码,并查看代码如何工作。 要执行代码,请在您的Spring Tool Suite或IntelliJ中将该应用程序作为Java应用程序运行。 在执行该应用程序时,您将看到类似于以下所示的输出。 它可能会略有不同,具体取决于您使用的库的版本。

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.3.RELEASE)

[info 2018/08/30 20:36:45.110 IST  tid=0x1] Starting App on MacBook-Air.local with PID 96473 (/Users/abhishekkothari/Documents/workspace-sts-3.9.5.RELEASE/pivotal_tutorial/target/classes started by abhishekkothari in /Users/abhishekkothari/Documents/workspace-sts-3.9.5.RELEASE/pivotal_tutorial)

[info 2018/08/30 20:36:45.118 IST  tid=0x1] No active profile set, falling back to default profiles: default

[info 2018/08/30 20:36:45.219 IST  tid=0x1] Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6c1a5b54: startup date [Thu Aug 30 20:36:45 IST 2018]; root of context hierarchy

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Entering into accessing data from Pivotal GemFire framework
	Abhishek Kothari is 26 years old
	Sumit Punjabi is 25 years old
	John Doe is 34 years old
Saving Alice, Bob and Carol to Pivotal GemFire...
Lookup each person by name...
	Abhishek Kothari is 26 years old
	Sumit Punjabi is 25 years old
	John Doe is 34 years old
Query adults (over 18):
	Sumit Punjabi is 25 years old
	John Doe is 34 years old
	Abhishek Kothari is 26 years old
Query teens (less than 30):
	Sumit Punjabi is 25 years old
	Abhishek Kothari is 26 years old
Query teens (between 12 and 30):
	Sumit Punjabi is 25 years old
	Abhishek Kothari is 26 years old

可以看出,该应用程序已执行,并且提取的lamba函数根据指定的过滤器使用数据。 请注意,这里我们创建了一个完成实体,存储并检索它,而没有真正对Pivotal gemfire数据库进行任何设置。 这些查询返回了我们这些实例,而没有进行任何大的努力。 通过这种方式,Spring Data批注有助于简化Pivotal Gemfire应用程序的应用程序开发,并帮助您减少从头开始进行编码和设置的整个工作量。

为了构建该应用程序并将其导出到其他地方以供远程使用,您需要做的就是使用Maven来构建应用程序jar。 为此,只需执行以下命令。

./mvnw spring-boot:run

上面的命令将构建一个可运行的jar,供您在任何系统中执行。 因此,您可以使用带有Pivotal Gemfire数据分发的Spring Data Framework轻松构建可移植的应用程序。

10.下载项目

上面已经讨论过的STS项目可以在下面的链接中找到。

下载
您可以在此处下载此示例的完整源代码: pivotal-tutorial.zip

翻译自: https://www.javacodegeeks.com/2018/08/spring-data-pivotal-gemfire-tutorial.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值