A Guide to GemFire with Spring Data – 使用Spring数据的GemFire指南

最后修改: 2017年 3月 31日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

GemFire is a high performance distributed data management infrastructure that sits between application cluster and back-end data sources.

GemFire是一个高性能的分布式数据管理基础设施,位于应用程序集群和后端数据源之间。

With GemFire, data can be managed in-memory, which makes the access faster. Spring Data provides an easy configuration and access to GemFire from Spring application.

通过GemFire,可以在内存中管理数据,这使得访问速度更快。Spring Data提供了一个简单的配置和从Spring应用程序访问GemFire。

In this article, we’ll take a look at how we can use GemFire to meet our application’s caching requirements.

在这篇文章中,我们将看看如何使用GemFire来满足我们应用程序的缓存要求。

 

IMPORTANT UPDATE: The project spring-data-gemfire is no longer maintained and is not recommended for use in new projects. The Spring team recommends using Spring Data for Apache Geode instead. 

重要的更新项目 spring-data-gemfire 已不再维护,不建议在新项目中使用。Spring 团队建议使用 Spring Data for Apache Geode 来代替。

2. Maven Dependencies

2.Maven的依赖性

To make use of the Spring Data GemFire support, we first need to add the following dependency in our pom.xml:

为了利用Spring Data GemFire支持,我们首先需要在我们的pom.xml中添加以下依赖关系:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-gemfire</artifactId>
    <version>1.9.1.RELEASE</version>
</dependency>

The latest version of this dependency can be found here.

该依赖性的最新版本可以在这里找到。

3. GemFire Basic Features

3.GemFire的基本功能

3.1. Cache

3.1.缓存

The cache in the GemFire provides the essential data management services as well as manages the connectivity to other peers.

GemFire中的缓存提供基本的数据管理服务,并管理与其他对等体的连接。

The cache configuration (cache.xml) describes how the data will be distributed among different nodes:

缓存配置(cache.xml)描述了数据将如何在不同的节点之间分配。

<cache>
    <region name="region">
        <region-attributes>
            <cache-listener>
                <class-name>
                ...
                </class-name>
            </cache-listener>
        </region-attributes>
    </region>
    ...
</cache>

3.2. Regions

3.2.区域

Data regions are a logical grouping within a cache for a single data set.

数据区域是高速缓存中的一个逻辑分组,用于单个数据集。

Simply put, a region lets us store data in multiple VMs in the system without consideration to which node the data is stored within the cluster.

简单地说,一个区域让我们在系统中的多个虚拟机中存储数据,而不考虑数据存储在集群中的哪个节点。

Regions are classified into three broad categories:

区域被分为三大类。

  • Replicated region holds the complete set of data on each node. It gives a high read performance. Write operations are slower as the data update need to be propagated to each node:
    <region name="myRegion" refid="REPLICATE"/>
  • Partitioned region distributes the data so that each node only stores a part of region contents. A copy of the data is stored on one of the other nodes. It provides a good write performance.
    <region name="myRegion" refid="PARTITION"/>
  • Local region resides on the defining member node. There is no connectivity with other nodes within the cluster.
    <region name="myRegion" refid="LOCAL"/>

3.3. Query the Cache

3.3.查询缓冲区

GemFire provides a query language called OQL (Object Query Language) that allows us to refer to the objects stored in GemFire data regions. This is very similar to SQL in syntax. Let’s see how a very basic query looks like:

GemFire提供了一种叫做OQL(对象查询语言)的查询语言,允许我们引用存储在GemFire数据区域的对象。这在语法上与SQL非常相似。让我们看看一个非常基本的查询是什么样子的。

SELECT DISTINCT * FROM exampleRegion

选择 DISTINCT * FROM exampleRegion

GemFire’s QueryService provides methods to create the query object.

GemFire的QueryService提供方法来创建查询对象。

3.4. Data Serialization

3.4.数据序列化

To manage the data serialization-deserialization, GemFire provides options other than Java serialization that gives a higher performance, provides greater flexibility for data storage and data transfer, also support for different languages.

为了管理数据的序列化-反序列化,GemFire提供了除Java序列化之外的其他选项,这些选项具有更高的性能,为数据存储和数据传输提供更大的灵活性,也支持不同的语言。

With that in mind, GemFire has defined Portable Data eXchange(PDX) data format. PDX is a cross-language data format that provides a faster serialization and deserialization, by storing the data in the named field which can be accessed directly without the need of fully deserializing the object.

考虑到这一点,GemFire已经定义了Portable Data eXchange(PDX)数据格式。PDX是一种跨语言的数据格式,它提供了更快的序列化和反序列化,通过将数据存储在可以直接访问的命名字段中,而无需完全反序列化对象。

3.5. Function Execution

3.5.函数执行

In GemFire, a function can reside on a server and can be invoked from a client application or another server without the need to send the function code itself.

在GemFire中,一个函数可以驻留在服务器上,可以从客户端应用程序或其他服务器上调用,而不需要发送函数代码本身。

The caller can direct a data-dependent function to operate on a particular data set or can lead an independent data function to work on a particular server, member or member group.

调用者可以引导一个依赖数据的函数在一个特定的数据集上操作,也可以引导一个独立的数据函数在一个特定的服务器、成员或成员组上工作。

3.6. Continuous Querying

3.6.连续查询

With continuous querying, the clients subscribe to server side events by using SQL-type query filtering. The server sends all the events that modify the query results. The continuous querying event delivery uses the client/server subscription framework.

通过连续查询,客户通过使用SQL类型的查询过滤来订阅服务器端的事件。服务器会发送所有修改查询结果的事件。连续查询的事件传递使用客户/服务器订阅框架。

The syntax for a continuous query is similar to basic queries written in OQL. For example, a query which provides the latest stock data from Stock region can be written as:

连续查询的语法与用OQL编写的基本查询相似。例如,一个提供Stock区域最新股票数据的查询可以写成。

SELECT * from StockRegion s where s.stockStatus='active';

To get the status update from this query, an implementation of CQListener need to be attached with the StockRegion:

为了从这个查询中获得状态更新,需要将CQListener的实现与StockRegion:联系起来。

<cache>
    <region name="StockRegion>
        <region-attributes refid="REPLICATE">
            ...
            <cache-listener>
                <class-name>...</class-name>
            </cache-listener>
        ...
        </region-attributes>
    </region>
</cache>

4. Spring Data GemFire Support

4.Spring Data GemFire支持

4.1. Java Configuration

4.1. Java配置

To simplify configuration, Spring Data GemFire provides various annotations for configuring core GemFire components:

为了简化配置,Spring Data GemFire为配置核心GemFire组件提供了各种注释。

@Configuration
public class GemfireConfiguration {

    @Bean
    Properties gemfireProperties() {
        Properties gemfireProperties = new Properties();
        gemfireProperties.setProperty("name","SpringDataGemFireApplication");
        gemfireProperties.setProperty("mcast-port", "0");
        gemfireProperties.setProperty("log-level", "config");
        return gemfireProperties;
    }

    @Bean
    CacheFactoryBean gemfireCache() {
        CacheFactoryBean gemfireCache = new CacheFactoryBean();
        gemfireCache.setClose(true);
        gemfireCache.setProperties(gemfireProperties());
        return gemfireCache;
    }

    @Bean(name="employee")
    LocalRegionFactoryBean<String, Employee> getEmployee(final GemFireCache cache) {
        LocalRegionFactoryBean<String, Employee> employeeRegion = new LocalRegionFactoryBean();
        employeeRegion.setCache(cache);
        employeeRegion.setName("employee");
        // ...
        return employeeRegion;
    }
}

To set up the GemFire cache and region, we have to first setup few specific properties. Here mcast-port is set to zero, which indicates that this GemFire node is disabled for multicast discovery and distribution. These properties are then passed to CacheFactoryBean to create a GemFireCache instance.

为了设置GemFire缓存和区域,我们必须首先设置一些特定的属性。这里mcast-port被设置为零,这表明该GemFire节点被禁用于多播发现和分发。然后将这些属性传递给CacheFactoryBean,以创建一个GemFireCache实例。

Using GemFireCache bean, an instance of LocalRegionFatcoryBean is created which represents the region within the Cache for the Employee instances.

使用GemFireCachebean,LocalRegionFatcoryBean的实例被创建,它代表了Employee实例的Cache中的区域。

4.2. Entity Mapping

4.2.实体映射

The library provides support to map objects to be stored in GemFire grid. The mapping metadata is defined by using annotations at the domain classes:

该库提供了对要存储在GemFire网格中的映射对象的支持。映射元数据是通过使用域类的注释来定义的。

@Region("employee")
public class Employee {

    @Id
    public String name;
    public double salary;

    @PersistenceConstructor
    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    // standard getters/setters
}

In the example above, we used the following annotations:

在上面的例子中,我们使用了以下注释。

  • @Region, to specify the region instance of the Employee class
  • @Id, to annotate the property that shall be utilized as a cache key
  • @PersistenceConstructor, which helps to mark the one constructor that will be used to create entities, in case multiple constructors available

4.3. GemFire Repositories

4.3.GemFire存储库

Next, let’s have a look at a central component in Spring Data – the repository:

接下来,让我们看看Spring Data中的一个核心组件–存储库。

@Configuration
@EnableGemfireRepositories(basePackages
  = "com.baeldung.spring.data.gemfire.repository")
public class GemfireConfiguration {

    @Autowired
    EmployeeRepository employeeRepository;
    
    // ...
}

4.4. Oql Query Support

4.4.Oql查询支持

The repositories allow the definition of query methods to efficiently run the OQL queries against the region the managed entity is mapped to:

资源库允许定义查询方法,以有效地运行针对被管理实体映射到的区域的OQL查询。

@Repository
public interface EmployeeRepository extends   
  CrudRepository<Employee, String> {

    Employee findByName(String name);

    Iterable<Employee> findBySalaryGreaterThan(double salary);

    Iterable<Employee> findBySalaryLessThan(double salary);

    Iterable<Employee> 
      findBySalaryGreaterThanAndSalaryLessThan(double salary1, double salary2);
}

4.5. Function Execution Support

4.5.函数执行支持

We also have annotation support available – to simplify working with GemFire function execution.

我们还提供了注释支持–以简化与GemFire函数执行的工作。

There are two concerns to address when we make use of functions, the implementation, and the execution.

当我们使用函数时,有两个问题需要解决,即实施和执行。

Let’s see how a POJO can be exposed as a GemFire function using Spring Data annotations:

让我们看看如何使用Spring Data注解将POJO暴露为GemFire函数。

@Component
public class FunctionImpl {

    @GemfireFunction
    public void greeting(String message){
        // some logic
    }
 
    // ...
}

We need to activate the annotation processing explicitly for @GemfireFunction to work:

我们需要明确地激活注释处理,以便@GemfireFunction能够工作。

@Configuration
@EnableGemfireFunctions
public class GemfireConfiguration {
    // ...
}

For function execution, a process invoking a remote function need to provide calling arguments, a function id, the execution target (onServer, onRegion, onMember, etc.):

对于函数的执行,调用远程函数的进程需要提供调用参数、函数id、执行目标(onServer, onRegion, onMember,等等)。

@OnRegion(region="employee")
public interface FunctionExecution {
 
    @FunctionId("greeting")
    public void execute(String message);
    
    // ...
}

To enable the function execution annotation processing, we need to add to activate it using Spring’s component scanning capabilities:

为了启用函数执行注解处理,我们需要添加使用Spring的组件扫描功能来激活它。

@Configuration
@EnableGemfireFunctionExecutions(
  basePackages = "com.baeldung.spring.data.gemfire.function")
public class GemfireConfiguration {
    // ...
}

5. Conclusion

5.结论

In this article, we have explored GemFire essential features and examined how Spring Data provided APIs make it easy to work with it.

在这篇文章中,我们探讨了GemFire的基本功能,并研究了Spring Data提供的API是如何使其易于工作的。

The complete code for this article is available over on GitHub.

本文的完整代码可在GitHub上获得