[[bootstrap:region]]
= Configuring a GemFire Region

A region is required to store and retrieve data from the cache. `Region` is an interface extending `java.util.Map` and enables basic data access using familiar key-value semantics. The `Region` interface is wired into classes that require it so the actual region type is decoupled from the programming model . Typically each region is associated with one domain object, similar to a table in a relational database.

GemFire implements the following types of regions:

* *Replicated* - Data is replicated across all cache members that define the region. This provides very high read performance but writes take longer to perform the replication.
* *Partioned* - Data is partitioned into buckets among cache members that define the region. This provides high read and write performance and is suitable for very large data sets that are too big for a single node.
* *Local* - Data only exists on the local node.
* *Client* - Technically a client region is a local region that acts as a proxy to a replicated or partitioned region hosted on cache servers. It may hold data created or fetched locally. Alternately, it can be empty. Local updates are synchronized to the cache server. Also, a client region may subscribe to events in order to stay synchronized with changes originating from remote processes that access the same region.

For more information about the various region types and their capabilities as well as configuration options, please refer to the GemFire Developer's http://gemfire.docs.pivotal.io/latest/userguide/index.html#developing/book_intro.html[Guide] and community http://www.pivotal.io/big-data/pivotal-gemfire[site].

[[bootstrap:region:lookup]]
== Using an externally configured Region

For referencing Regions already configured through GemFire `cache.xml` file, use the `lookup-region` element. Simply declare the target Region name with the`name` attribute;
for example, to declare a bean definition named `region-bean` for an existing region named `Orders` one can use the following bean definition:

[source,xml]
----
<gfe:lookup-region id="region-bean" name="Orders"/>
----

If the `name` is not specified, the bean's `id` will be used. The example above becomes:

[source,xml]
----
<!-- lookup for a region called 'Orders' -->
<gfe:lookup-region id="Orders"/>
----

NOTE: If the Region does not exist, an initialization exception will be thrown. For configuring new GemFire Regions, proceed to the appropriate sections below.

Note, in the previous examples, since no cache name was defined, the default naming convention (`gemfireCache`) was used. Alternately, one can reference the cache bean through the `cache-ref` attribute:

[source,xml]
----
<gfe:cache id="cache"/>
<gfe:lookup-region id="region-bean" name="Orders" cache-ref="cache"/>
----

`lookup-region` provides a simple way of retrieving existing, pre-configured Regions without exposing the Region semantics or setup infrastructure.

[[bootstrap:region:auto-lookup]]
== Auto Region Lookup

New, as of Spring Date GemFire 1.5, is the ability to "auto-lookup" all Regions defined in GemFire's native cache.xml file, and imported into Spring config
using the`cache-xml-location` attribute on the `<gfe:cache>` element in the GFE XML namespace.

For instance, given a GemFire `cache.xml` file of...

[source,xml]
----
<?xml version="1.0"?>
<!DOCTYPE cache PUBLIC  "-//GemStone Systems, Inc.//GemFire Declarative Caching 7.0//EN"
	"http://www.gemstone.com/dtd/cache7_0.dtd">
<cache>
	<region name="Parent" refid="REPLICATE">
		<region name="Child" refid="REPLICATE"/>
	</region>
</cache>
----

A user may import the `cache.xml` file as follows...

[source,xml]
----
<gfe:cache cache-xml-location="cache.xml"/>
----

A user can then use the `<gfe:lookup-region>` element (e.g. `<gfe:lookup-region id="Parent"/>`) to reference specific
GemFire Regions as bean in the Spring context, or the user may choose to import all GemFire Regions defined
in `cache.xml` with the new...

[source,xml]
----
<gfe:auto-region-lookup/>
----

Spring Data GemFire will automatically create Spring beans referencing all GemFire Regions defined in `cache.xml`
that have not been explicitly added to the Spring context with `<gfe:lookup-region>` bean declarations.

It is important to realize that Spring Data GemFire uses a Spring http://docs.spring.io/spring/docs/4.0.7.RELEASE/javadoc-api/org/springframework/beans/factory/config/BeanPostProcessor.html[BeanPostProcessor]
to post process the Cache after it is both created and initialized to determine the Regions defined in GemFire to add
as beans in the Spring context.

You may inject these "auto-looked-up" Regions like any other bean defined in the Spring context with 1 exception; you
may need to define a `depends-on` association with the '`gemfireCache`' bean as follows...

[source,java]
----

package example;

import ...

@Repository("appDao")
@DependsOn("gemfireCache")
public class ApplicationDao extends DaoSupport {

  @Resource(name = "Parent")
  private Region<?, ?> parent;

  @Resource(name = "/Parent/Child")
  private Region<?, ?> child;

  ...
}
----

The above Java example is applicable when using the Spring context's `component-scan` functionality.

If you are declaring your components using Spring XML, then you would...

[source,xml]
----
<bean class="example.ApplicationDao" depends-on="gemfireCache"/>
----

This ensures the GemFire Cache and all the Regions defined in `cache.xml` get created before any components
with auto-wire references when using the new `<gfe:auto-region-lookup>` element.

[[bootstrap:region:overview]]
== Configuring Regions

Spring Data GemFire provides comprehensive support for configuring any type of GemFire Region via the following elements:

* Local Region `<local-region>`
* Replicated Region `<replicated-region>`
* Partitioned Region `<partitioned-region>`
* Client Region `<client-region>`

For a comprehensive description of http://gemfire.docs.pivotal.io/latest/userguide/index.html#developing/region_options/region_types.html[Region types] please consult the GemFire product documentation.

[[bootstrap:region:common:attributes]]
=== Common Region Attributes

The following table(s) list attributes available for various region types:

[cols="1,2,2", options="header"]
.Common Region Attributes
|===
| Name
| Values
| Description

| cache-ref
| *GemFire Cache bean name*
| The name of the bean defining the GemFire Cache (by default 'gemfireCache').

| close
| *boolean, default:false (Note: The default was true prior to 1.3.0)*
| Indicates whether the Region should be closed at shutdown.

| cloning-enabled
| *boolean, default:false*
| When true, the updates are applied to a clone of the value and then the clone is saved to the cache. When false, the value is modified in place in the cache.

| concurrency-checks-enabled
| *boolean, default:true*
| Determines whether members perform checks to provide consistent handling for concurrent or out-of-order updates to distributed Regions.

| data-policy
| *See GemFire's http://gemfire.docs.pivotal.io/7.0.2/javadocs/japi/index.html[Data Policy]*
| The Region's Data Policy. Note, not all Data Policies are supported for every Region type.

| destroy
| *boolean, default:false*
| Indicates whether the Region should be destroyed at shutdown.

| disk-store-ref
| *The name of a configured Disk Store.*
| A reference to a bean created via the `disk-store` element.

| disk-synchronous
| *boolean, default:true*
| Indicates whether Disk Store writes are synchronous.

| enable-gateway
| *boolean, default:false*
| Indicates whether the Region will synchronize entries over a WAN Gateway.

| hub-id
| *The name of the Gateway Hub.*
| This will automatically set enable-gateway to true. If enable-gateway is explicitly set to false, an exception will be thrown.

| id
| *Any valid bean name.*
| Will also be the Region name by default.

| ignore-if-exists
| *boolean, default:false*
| Ignores this bean definition configuration if the Region already exists in the GemFire Cache, resulting in a lookup instead.

| ignore-jta
| *boolean, default:false*
| Indicates whether the Region participates in JTA transactions.

| index-update-type
| *synchronous or asynchronous, default:synchronous*
| Indicates whether indices will be updated synchronously or asynchronously on entry creation.

| initial-capacity
| *integer, default:16*
| The initial memory allocation for number of Region entries.

| key-constraint
| *Any valid, fully-qualified Java class name.*
| The expected key type.

| load-factor
| *float, default:.75*
| Sets the initial parameters on the underlying java.util.ConcurrentHashMap used for storing Region entries.

| name
| *Any valid Region name.*
| The name of the Region definition. If not specified, it will assume the value of the id attribute (the bean name).

| persistent
| *boolean, default:false*
| Indicates whether the Region persists entries to a Disk Store (disk).

| shorcut
| *See http://gemfire.docs.pivotal.io/7.0.2/javadocs/japi/com/gemstone/gemfire/cache/RegionShortcut.html
| The RegionShortcut for this Region. Allows easy initialization of the region based on pre-defined defaults.

| statistics
| *boolean, default:false*
| Indicates whether the Region reports statistics.

| template
| *The name of a Region Template.*
| A reference to a bean created via one of the `*region-template` elements.

| value-constraint
| *Any valid, fully-qualified Java class name.*
| The expected value type.
|===

[[bootstrap:region:common:cache-listener]]
=== Cache Listeners

Cache Listeners are registered with a region to handle region events such as entries being created, updated, destroyed, etc. A Cache Listener can be any bean that implements the http://gemfire.docs.pivotal.io/7.0.2/javadocs/japi/com/gemstone/gemfire/cache/CacheListener.html[`CacheListener`] interface. A region may have multiple listeners, declared using the `cache-listener` element enclosed in a `*-region` element. In the example below, there are two `CacheListener`s declared. The first references a top-level named Spring bean; the second is an anonymous inner bean definition.

[source,xml]
----
<gfe:replicated-region id="region-with-listeners">
    <gfe:cache-listener>
        <!-- nested cache listener reference -->
        <ref bean="c-listener"/>
        <!-- nested cache listener declaration -->
        <bean class="some.pkg.AnotherSimpleCacheListener"/>
    </gfe:cache-listener>

    <bean id="c-listener" class="some.pkg.SimpleCacheListener"/>
</gfe:replicated-region>
----

The following example uses an alternate form of the `cache-listener` element with a `ref` attribute. This allows for more concise configuration for a single cache listener. Note that the namespace only allows a single `cache-listener` element so either the style above or below must be used.

WARNING: Using `ref` and a nested declaration in a `cache-listener`, or similar element, is illegal. The two options are mutually exclusive and using both on the same element will result in an exception.

[source,xml]
----
<beans>
    <gfe:replicated-region id="region-with-one listener">
        <gfe:cache-listener ref="c-listener"/>
    </gfe:replicated-region>

    <bean id="c-listener" class="some.pkg.SimpleCacheListener"/>
 </beans>
    
----

.Bean Reference Conventions
[NOTE]
====
The `cache-listener` element is an example of a common pattern used in the namespace anywhere GemFire provides a callback interface to be implemented in order to invoke custom code in response to cache or region events. Using Spring's IoC container, the implementation is a standard Spring bean. In order to simplify the configuration, the schema allows a single occurrence of the `cache-listener` element, but it may contain nested bean references and inner bean definitions in any combination if multiple instances are permitted. The convention is to use the singular form (i.e., `cache-listener` vs `cache-listeners`) reflecting that the most common scenario will in fact be a single instance. We have already seen examples of this pattern in the <<null,advanced cache>> configuration example.
====

[[bootstrap:region:common:loaders-writers]]
=== Cache Loaders and Cache Writers

Similar to `cache-listener`, the namespace provides `cache-loader` and `cache-writer` elements to register these respective components for a region. A `CacheLoader` is invoked on a cache miss to allow an entry to be loaded from an external data source, a database for example. A `CacheWriter` is invoked after an entry is created or updated, intended for synchronizing to an external data source. The difference is GemFire only supports at most a single instance of each for each region. However, either declaration style may be used. See http://gemfire.docs.pivotal.io/7.0.2/javadocs/japi/com/gemstone/gemfire/cache/CacheLoader.html[`CacheLoader`] and http://gemfire.docs.pivotal.io/7.0.2/javadocs/japi/com/gemstone/gemfire/cache/CacheWriter.html[`CacheWriter`] for more details.

[[bootstrap:region:common:subregions]]
=== Subregions

In Release 1.2.0, Spring Data GemFire added support for subregions, allowing regions to be arranged in a hierarchical relationship. For example, GemFire allows for a */Customer/Address* region and a different */Employee/Address* region. Additionally, a subregion may have it's own subregions and its own configuration. A subregion does not inherit attributes from the parent region. Regions types may be mixed and matched subject to GemFire constraints. A subregion is naturally declared as a child element of a region. The subregion's name attribute is the simple name. The above example might be configured as: [source,nonxml]
----
<beans>

    <gfe:replicated-region name="Customer">
        <gfe:replicated-region name="Address"/>
    </gfe:replicated-region>

    <gfe:replicated-region name="Employee">
        <gfe:replicated-region name="Address"/>
    </gfe:replicated-region>

</beans>
----

Note that the `Monospaced ([id])` attribute is not permitted for a subregion. The subregions will be created with bean names */Customer/Address* and */Employee/Address*, respectively. So they may be injected using the full path name into other beans that use them, such as `GemfireTemplate`. The full path should also be used in OQL query strings.

[[bootstrap:region:common:region-templates]]
== Region Templates

Also new as of Spring Data GemFire 1.5 is Region Templates.  This feature allows developers to define common Region
configuration settings and attributes once and reuse the configuration among many Region bean definitions declared
in the Spring context.

Spring Data GemFire introduces 5 new tags to the SDG XML namespace (XSD):

[cols="1,2", options="header"]
.Region Template Tags
|===
| Tag Name
| Description

| `<gfe:region-template>`
| Defines common, generic Region attributes; extends `regionType` in the SDG 1.5 XSD

| `<gfe:local-region-template>`
| Defines common, 'Local' Region attributes; extends `localRegionType` in the SDG 1.5 XSD

| `<gfe:partitioned-region-template>`
| Defines common, 'PARTITION' Region attributes; extends `partitionedRegionType` in the SDG 1.5 XSD

| `<gfe:replicated-region-template>`
| Defines common, 'REPLICATE' Region attributes; extends `replicatedRegionType` in the SDG 1.5 XSD

| `<gfe:client-region-template>`
| Defines common, 'Client' Region attributes; extends `clientRegionType` in the SDG 1.5 XSD
|===

In addition to the new tags, `<gfe:*-region>` elements along with the `<gfe:*-region-template>` elements have
a `template` attribute used to define the Region Template from which to inherit the Region configuration.  Even
Region templates may inherit from other Region Templates.

Here is an example of 1 possible configuration...

[source,xml]
----
<gfe:async-event-queue id="AEQ" persistent="false" parallel="false" dispatcher-threads="4">
  <gfe:async-event-listener>
    <bean class="example.AeqListener"/>
  </gfe:async-event-listener>
</gfe:async-event-queue>

<gfe:region-template id="BaseRegionTemplate" cloning-enabled="true"
    concurrency-checks-enabled="false" disk-synchronous="false"
    ignore-jta="true" initial-capacity="51" key-constraint="java.lang.Long"
    load-factor="0.85" persistent="false" statistics="true"
    value-constraint="java.lang.String">
  <gfe:cache-listener>
    <bean class="example.CacheListenerOne"/>
    <bean class="example.CacheListenerTwo"/>
  </gfe:cache-listener>
  <gfe:entry-ttl timeout="300" action="INVALIDATE"/>
  <gfe:entry-tti timeout="600" action="DESTROY"/>
</gfe:region-template>

<gfe:region-template id="ExtendedRegionTemplate" template="BaseRegionTemplate"
    index-update-type="asynchronous" cloning-enabled="false"
    concurrency-checks-enabled="true" key-constraint="java.lang.Integer"
    load-factor="0.55">
  <gfe:cache-loader>
    <bean class="example.CacheLoader"/>
  </gfe:cache-loader>
  <gfe:cache-writer>
    <bean class="example.CacheWriter"/>
  </gfe:cache-writer>
  <gfe:membership-attributes required-roles="readWriteNode" loss-action="limited-access" resumption-action="none"/>
  <gfe:async-event-queue-ref bean="AEQ"/>
</gfe:region-template>

<gfe:partitioned-region-template id="PartitionRegionTemplate" template="ExtendedRegionTemplate"
    copies="1" local-max-memory="1024" total-max-memory="16384" recovery-delay="60000"
    startup-recovery-delay="15000" enable-async-conflation="false"
    enable-subscription-conflation="true" load-factor="0.70"
    value-constraint="java.lang.Object">
  <gfe:partition-resolver>
    <bean class="example.PartitionResolver"/>
  </gfe:partition-resolver>
  <gfe:eviction type="ENTRY_COUNT" threshold="8192000" action="OVERFLOW_TO_DISK"/>
</gfe:partitioned-region-template>

<gfe:partitioned-region id="TemplateBasedPartitionRegion" template="PartitionRegionTemplate"
    copies="2" local-max-memory="8192" total-buckets="91" disk-synchronous="true"
    enable-async-conflation="true" ignore-jta="false" key-constraint="java.util.Date"
    persistent="true">
  <gfe:cache-writer>
    <bean class="example.CacheWriter"/>
  </gfe:cache-writer>
  <gfe:membership-attributes required-roles="admin,root" loss-action="no-access" resumption-action="reinitialize"/>
  <gfe:partition-listener>
    <bean class="example.PartitionListener"/>
  </gfe:partition-listener>
  <gfe:subscription type="ALL"/>
</gfe:partitioned-region>
----

Region Templates will even work for Subregions.  Notice that 'TemplateBasedPartitionRegion' extends 'PartitionRegionTemplate'
which extends 'ExtendedRegionTemplate' which extends 'BaseRegionTemplate'.  Attributes and sub-elements defined in
subsequent, inherited Region bean definitions override what is in the parent.

=== Under the hood...

Spring Data GemFire applies Region Templates when the Spring application context configuration meta-data is *parsed*,
and therefore, must be declared in the order of inheritance, in other words, parent templates before children.  This
ensure the proper configuration is applied, especially when element attributes or sub-elements are "overridden".

IMPORTANT: It is equally important to remember the Region types must only inherit from other similar typed Region.
For instance, it is not possible for a `<gfe:replicated-region>` to inherit from a `<gfe:partitioned-region-template>`.

NOTE: Region Templates are single-inheritance.

[[bootstrap:region:common:regions-subregions-lookups-caution]]
== A Word of Caution on Regions, Subregions and Lookups

Prior to Spring Data GemFire 1.4, one of the underlying properties of the high-level `replicated-region`,
`partitioned-region`, `local-region` and `client-region` elements in Spring Data GemFire's XML namespace,
which correspond to GemFire's Region types based on Data Policy, is that these elements perform a lookup first
before attempting to create the region. This is done in case the region already exists, which might be the case
if the region was defined in GemFire's native configuration, e.g. `cache.xml`, thereby avoiding any errors.
This was by design, though subject to change.

WARNING: The Spring team highly recommends that the `replicated-region`, `partitioned-region`, `local-region`
and `client-region` elements be strictly used only for defining new regions. One of the problems with these elements
doing a lookup first is, if the developer assumed that defining a bean definition for a REPLICATE region would create
a new region, however, consequently a region with the same name already exists having different semantics for
eviction, expiration, subscription and/or other attributes, this could adversely affect application logic
and/or expectations thereby violating application requirements.

IMPORTANT: Recommended Practice - Only use the `replicated-region`, `partitioned-region`, `local-region`
and `client-region` XML namespace elements for defining new regions.

However, because the high-level region elements perform a lookup first, this can cause problems for
dependency injected region resources to application code, like DAOs or Repositories.

Take for instance the following native GemFire configuration file (e.g. `cachel.xml`)...

[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE cache PUBLIC  "-//GemStone Systems, Inc.//GemFire Declarative Caching 7.0//EN"
"http://www.gemstone.com/dtd/cache7_0.dtd">
<cache>
    <region name="Customers" refid="REPLICATE">
	    <region name="Accounts" refid="REPLICATE">
		    <region name="Orders" refid="REPLICATE">
			    <region name="Items" refid="REPLICATE"/>
            </region>
        </region>
    </region>
</cache>
----

Also, consider that you might have defined a DAO as follows...

[source,java]
----
public class CustomerAccountDao extends GemDaoSupport {

    @Resource(name = "Customers/Accounts")
    private Region customersAccounts;

    ...
}
----

Here, we are injecting a reference to the `Customers/Accounts` GemFire Region in our DAO. As such, it is not uncommon for a developer to define beans for all or some of these regions in Spring XML configuration meta-data as follows...

[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:gfe="http://www.springframework.org/schema/gemfire"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd">

    <gfe:cache cache-xml-location="classpath:cache.xml"/>

    <gfe:lookup-region name="Customers/Accounts"/>
    <gfe:lookup-region name="Customers/Accounts/Orders"/>
</beans>
----

Here the `Customers/Accounts` and `Customers/Accounts/Orders` GemFire Regions are referenced as beans in the Spring context as "Customers/Accounts" and "Customers/Accounts/Orders", respectively. The nice thing about using the `lookup-region` element and the corresponding syntax above is that it allows a developer to reference a subregion directly without unnecessarily defining a bean for the parent region (e.g. `Customers`).

However, if now the developer changes his/her configuration meta-data syntax to using the nested format, like so...

[source,xml]
----
<gfe:lookup-region name="Customers">
    <gfe:lookup-region name="Accounts">
        <gfe:lookup-region name="Orders"/>
    </gfe:lookup-region>
</gfe:lookup-region>
----

Or, perhaps the developer erroneously chooses to use the high-level `replicated-region` element, which will do a lookup first, as in...

[source,xml]
----
<gfe:replicated-region name="Customers" persistent="true">
    <gfe:replicated-region name="Accounts" persistent="true">
        <gfe:replicated-region name="Orders" persistent="true"/>
    </gfe:replicated-region>
</gfe:replicated-region>
----

Then the region beans defined in the Spring context will consist of the following: `{ "Customers", "/Customers/Accounts", "/Customers/Accounts/Orders" }.` This means the dependency injected reference (i.e. `@Resource(name = "Customers/Accounts"))` is now broken since no bean with name "Customers/Accounts" is defined.

GemFire is flexible in referencing both parent regions and subregions. The parent can be referenced as "/Customers" or "Customers" and the child as "/Customers/Accounts" or just "Customers/Accounts". However, Spring Data GemFire is very specific when it comes to naming beans after regions, typically always using the forward slash (/) to represents subregions (e.g. "/Customers/Accounts").

Therefore, it is recommended that users use either the nested `lookup-region` syntax as illustrated above, or define direct references with a leading forward slash (/) like so...

[source,xml]
----
<gfe:lookup-region name="/Customers/Accounts"/>
<gfe:lookup-region name="/Customers/Accounts/Orders"/>
----

The example above where the nested `replicated-region` elements were used to reference the subregions serves to illustrate the problem stated earlier. Are the Customers, Accounts and Orders Regions/Subregions persistent or not? Not, since the regions were defined in native GemFire configuration (i.e. `cache.xml`) and will exist by the time the cache is initialized, or once the `<gfe:cache>` bean is created. Since the high-level region XML namespace abstractions, like `replicated-region`, perform the lookup first, it uses the regions as defined in the `cache.xml` configuration file.

[[bootstrap:region:persistence]]
== Data Persistence

Regions can be made persistent. GemFire ensures that all the data you put into a region that is configured for persistence will be written to disk in a way that it can be recovered the next time you create the region. This allows data to be recovered after a machine or process failure or after an orderly shutdown and restart of GemFire.

To enable persistence with Spring Data GemFire, simply set the `persistent` attribute to true:

[source,xml]
----
<gfe:partitioned-region id="persitent-partition" persistent="true"/>
----

IMPORTANT: Persistence for partitioned regions is supported from GemFire 6.5 onwards - configuring this option on a previous release will trigger an initialization exception.

Persistence may also be configured using the `data-policy` attribute, set to one of http://gemfire.docs.pivotal.io/7.0.2/javadocs/japi/com/gemstone/gemfire/cache/DataPolicy.html[GemFire's data policy settings]. For instance...

[source,xml]
----
<gfe:partitioned-region id="persitent-partition" data-policy="PERSISTENT_PARTITION"/>
----

The data policy must match the region type and must also agree with the `persistent` attribute if explicitly set. An initialization exception will be thrown if, for instance, the `persistent` attribute is set to false, yet a persistent data policy was specified.

When persisting regions, it is recommended to configure the storage through the `disk-store` element for maximum efficiency. The diskstore is referenced using the disk-store-ref attribute. Additionally, the region may perform disk writes synchronously or asynchronously:

[source,xml]
----
<gfe:partitioned-region id="persitent-partition" persistent="true" disk-store-ref="myDiskStore" disk-synchronous="true"/>
----

This is discussed further in <<bootstrap-diskstore>>

[[bootstrap:region:subscription]]
== Subscription Interest Policy

GemFire allows configuration of subscriptions to control http://gemfire.docs.pivotal.io/latest/userguide/index.html#developing/events/configure_p2p_event_messaging.html[peer to peer event handling]. Spring Data GemFire provides a `<gfe:subscription/>` to set the interest policy on replicated and partitioned regions to either `ALL` or `CACHE_CONTENT`.

[source,xml]
----
<gfe:partitioned-region id="subscription-partition">
     <gfe:subscription type="CACHE_CONTENT"/>
</gfe:partitioned-region>
----

[[bootstrap:region:eviction]]
== Data Eviction and Overflowing

Based on various constraints, each region can have an eviction policy in place for evicting data from memory. Currently, in GemFire, eviction applies to the least recently used entry (also known as http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used[LRU]). Evicted entries are either destroyed or paged to disk (also known as *overflow*).

Spring Data GemFire supports all eviction policies (entry count, memory and heap usage) for both `partitioned-region` and `replicated-region` as well as `client-region`, through the nested `eviction` element. For example, to configure a partition to overflow to disk if its size is more then 512 MB, one could use the following configuration:

[source,xml]
----
<gfe:partitioned-region id="overflow-partition">
     <gfe:eviction type="MEMORY_SIZE" threshold="512" action="OVERFLOW_TO_DISK"/>
</gfe:partitioned-region>
----

IMPORTANT: Replicas cannot use a `local destroy` eviction since that would invalidate them. See the GemFire docs for more information.

When configuring regions for overflow, it is recommended to configure the storage through the `disk-store` element for maximum efficiency.

For a detailed description of eviction policies, see the GemFire documentation (such as http://gemfire.docs.pivotal.io/latest/userguide/index.html#developing/eviction/how_eviction_works.html[this] page).

== Data Expiration

GemFire allows you to control how long entries exist in the cache. Eviction is driven by elapsed time, as opposed to eviction which is driven by memory usage. Once an entry expires it may no longer be accessed from the cache. GemFire supports the following expiration types:

* *Time to live (TTL)* - The amount of time, in seconds, the object may remain in the cache after the last creation or update. For entries, the counter is set to zero for create and put operations. Region counters are reset when the region is created and when an entry has its counter reset.
* *Idle timeout* - The amount of time, in seconds, the object may remain in the cache after the last access. The idle timeout counter for an object is reset any time its TTL counter is reset. In addition, an entry’s idle timeout counter is reset any time the entry is accessed through a get operation or a netSearch . The idle timeout counter for a region is reset whenever the idle timeout is reset for one of its entries.

Each of these may be applied to the region itself or entries in the region. Spring Data GemFire provides `<region-ttl>`, `<region-tti>`, `<entry-ttl>` and `<entry-tti>` region child elements to specify timeout values and expiration actions.

[[bootstrap:region:local]]
== Local Region

Spring Data GemFire offers a dedicated `local-region` element for creating local regions. Local regions, as the name implies, are standalone meaning they do not share data with any other distributed system member. Other than that, all common region configuration options are supported. A minimal declaration looks as follows (again, the example relies on the Spring Data GemFire namespace naming conventions to wire the cache):

[source,xml]
----
<gfe:local-region id="myLocalRegion" />
----

Here, a local region is created (if one doesn't exist already). The name of the region is the same as the bean id (myLocalRegion) and the bean assumes the existence of a GemFire cache named `gemfireCache`.

[[bootstrap:region:replicate]]
== Replicated Region

One of the common region types is a *replicated region* or *replica*. In short, when a region is configured to be a replicated region, every member that hosts that region stores a copy of the region's entries locally. Any update to a replicated region is distributed to all copies of the region. When a replica is created, it goes through an initialization stage in which it discovers other replicas and automatically copies all the entries. While one replica is initializing you can still continue to use the other rep

Spring Data GemFire offers a `replicated-region` element. A minimal declaration looks as follows. All common configuration options are available for replicated regions.

[source,xml]
----
<gfe:replicated-region id="simpleReplica" />
----

[[bootstrap:region:partition]]
== Partitioned Region

Another region type supported out of the box by the Spring Data GemFire namespace is the partitioned region. To quote the GemFire docs:

"A partitioned region is a region where data is divided between peer servers hosting the region so that each peer stores a subset of the data. When using a partitioned region, applications are presented with a logical view of the region that looks like a single map containing all of the data in the region. Reads or writes to this map are transparently routed to the peer that hosts the entry that is the target of the operation. [...] GemFire divides the domain of hashcodes into buckets. Each bucket is assigned to a specific peer, but may be relocated at any time to another peer in order to improve the utilization of resources across the cluster."

A partition is created using the `partitioned-region` element. Its configuration options are similar to that of the `replicated-region` plus the partion specific features such as the number of redundant copies, total maximum memory, number of buckets, partition resolver and so on. Below is a quick example on setting up a partition region with 2 redundant copies:

[source,xml]
----
<!-- bean definition named 'distributed-partition' backed by a region named 'redundant' with 2 copies
and a nested resolver declaration  -->
<gfe:partitioned-region id="distributed-partition" copies="2" total-buckets="4" name="redundant">
    <gfe:partition-resolver>
        <bean class="some.pkg.SimplePartitionResolver"/>
    </gfe:partition-resolver>
</gfe:partitioned-region>
----

[[bootstrap:region:partition:options]]
=== `partitioned-region` Options

The following table offers a quick overview of configuration options specific to partitioned regions. These are in addition to the common region configuration options described above.

[cols="1,2,2", options="header"]
.partitioned-region options
|===
| Name
| Values
| Description

| partition-resolver
| *bean name*
| The name of the partitioned resolver used by this region, for custom partitioning.

| partition-listener
| *bean name*
| The name of the partitioned listener used by this region, for handling partition events.

| copies
| 0..4
| The number of copies for each partition for high-availability. By default, no copies are created meaning there is no redundancy. Each copy provides extra backup at the expense of extra storage.

| colocated-with
| *valid region name*
| The name of the partitioned region with which this newly created partitioned region is colocated.

| local-max-memory
| *positive integer*
| The maximum amount of memory, in megabytes, to be used by the region in *this* process.

| total-max-memory
| *any integer value*
| The maximum amount of memory, in megabytes, to be used by the region in *all* processes.

| recovery-delay
| *any long value*
| The delay in milliseconds that existing members will wait before satisfying redundancy after another member crashes. -1 (the default) indicates that redundancy will not be recovered after a failure.

| startup-recovery-delay
| *any long value*
| The delay in milliseconds that new members will wait before satisfying redundancy. -1 indicates that adding new members will not trigger redundancy recovery. The default is to recover redundancy immediately when a new member is added.

|===

[[bootstrap:region:client]]
== Client Region

GemFire supports various deployment topologies for managing and distributing data. The topic is outside the scope of this documentation however to quickly recap, they can be classified in short in: peer-to-peer (p2p), client-server, and wide area cache network (or WAN). In the last two scenarios, it is common to declare *client* regions which connect to a cache server. Spring Data GemFire offers dedicated support for such configuration through <<bootstrap:cache:client>>, `client-region` and `pool` elements. As the names imply, the former defines a client region while the latter defines connection pools to be used/shared by the various client regions.

Below is a typical client region configuration:

[source,xml]
----
<!-- client region using the default client-cache pool -->
<gfe:client-region id="simple">
    <gfe:cache-listener ref="c-listener"/>
</gfe:client-region>

<!-- region using its own dedicated pool -->
<gfe:client-region id="complex" pool-name="gemfire-pool">
    <gfe:cache-listener ref="c-listener"/>
</gfe:client-region>

<bean id="c-listener" class="some.pkg.SimpleCacheListener"/>

<!-- pool declaration -->
<gfe:pool id="gemfire-pool" subscription-enabled="true">
    <gfe:locator host="someHost" port="40403"/>
</gfe:pool>
----

As with the other region types, `client-region` supports `CacheListener``s` as well as a single `CacheLoader` or `CacheWriter`. It also requires a connection `pool` for connecting to a server. Each client can have its own pool or they can share the same one.

NOTE: In the above example, the pool is configured with a `locator`. The locator is a separate process used to discover cache servers in the distributed system and are recommended for production systems. It is also possible to configure the pool to connect directly to one or more cache servers using the `server` element.

For a full list of options to set on the client and especially on the pool, please refer to the Spring Data GemFire schema (<<appendix-schema>>) and the GemFire documentation.

[[bootstrap:region:client:interests]]
=== Client Interests

To minimize network traffic, each client can define its own 'interest', pointing out to GemFire, the data it actually needs. In Spring Data GemFire, interests can be defined for each client, both key-based and regular-expression-based types being supported; for example:

[source,xml]
----
<gfe:client-region id="complex" pool-name="gemfire-pool">
    <gfe:key-interest durable="true" result-policy="KEYS">
        <bean id="key" class="java.lang.String">
             <constructor-arg value="someKey" />
        </bean>
    </gfe:key-interest>
    <gfe:regex-interest pattern=".*" receive-values="false"/>
</gfe:client-region>
----

A special key `ALL_KEYS` means interest is registered for all keys (identical to a regex interest of `.*`). The `receive-values` attribute indicates whether or not the values are received for create and update events. If true, values are received; if false, only invalidation events are received - refer to the GemFire documentation for more details.

[[bootstrap:region:json]]
== JSON Support

Gemfire 7.0 introduced support for caching JSON documents with OQL query support. These are stored internally as http://gemfire.docs.pivotal.io/latest/javadocs/japi/com/gemstone/gemfire/pdx/PdxInstance.html[PdxInstance] types using the http://gemfire.docs.pivotal.io/latest/javadocs/japi/com/gemstone/gemfire/pdx/JSONFormatter.html[JSONFormatter] to perform conversion to and from JSON strings. Spring Data GemFire provides a `<gfe-data:json-region-autoproxy/>` tag to enable a http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#aop-introduction[AOP with Spring] component to advise appropriate region operations, effectively encapsulating the JSONFormatter, allowing your application to work directly with JSON strings. In addition, Java objects written to JSON configured regions will be automatically converted to JSON using the Jackson ObjectMapper. Reading these values will return a JSON string.

By default, `<gfe-data:json-region-autoproxy/>` will perform the conversion on all regions. To apply this feature to selected regions, provide a comma delimited list of their ids via the `region-refs` attribute. Other attributes include a `pretty-print` flag (false by default) and `convert-returned-collections`. By default the results of region operations getAll() and values() will be converted for configured regions. This is done by creating a parallel structure in local memory. This can incur significant overhead for large collections. Set this flag to false to disable automatic conversion for these operation. NOTE: Certain region operations, specifically those that use GemFire's proprietary Region.Entry such as entries(boolean), entrySet(boolean) and getEntry() type are not targeted for AOP advice. In addition, the entrySet() method which returns a Set<java.util.Map.Entry<?,?>> is not affected.

[source,xml]
----
<gfe-data:json-region-autoproxy pretty-print="true" region-refs="myJsonRegion" convert-returned-collections="true"/>
----

This feature also works with seamlessly with GemfireTemplate operations, provided that the template is declared as a Spring bean. Currently native QueryService operations are not supported.

