101
Pivotal GemFire® Native Client 10.0 Rev: 10.0.5 © Copyright Pivotal Software Inc, 2013-2020

Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

PivotalGemFire®NativeClient10.0

Rev:10.0.5

©CopyrightPivotalSoftwareInc,2013-2020

Page 2: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

2347

1220212528303435404345525661626565666875808489

TableofContents

TableofContentsPivotalGemFireNativeClient10.0DocumentationGemFireNativeClientReleaseNotesSystemRequirementsUpgradingaNativeClientApplicationFromVersion9toVersion10InstallingtheNativeLibraryGettingStartedwiththeNativeLibraryPut/Get/RemoveExamplesConfiguringaClientApplicationSystemLevelConfigurationConfiguringtheClientCacheConfiguringRegionsRegisteringInterestforEntriesRegionAttributesSerializingDataRemoteQueriesContinuousQueriesSecurity:AuthenticationandEncryptionAuthenticationTLS/SSLClient-ServerCommunicationEncryptionSetUpOpenSSLStartingandstoppingtheclientandserverwithSSLinplaceFunctionExecutionTransactionsSessionStateProviderSystemPropertiesClientCacheXMLReference

©CopyrightPivotalSoftwareInc,2013-2019 2 10.0

Page 3: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

PivotalGemFireNativeClient10.0DocumentationPublishedMay4,2020

ThePivotalGemFireNativeClientisalibrarythatprovidesaccessforC++andMicrosoft .NET™clientstoaGemFiredistributedsystem.

SeetheReleaseNotesfornewfeaturesandsupportinformationregardingthisrelease.

SeetheAPIdocsforAPIdetails:

C++APIdocs

.NETAPIdocs

SeethePivotalGemFireUserGuide forinformationregardingtheserver.

®

©CopyrightPivotalSoftwareInc,2013-2019 3 10.0

Page 4: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

GemFireNativeClientReleaseNotesInthistopic

IssuesResolvedinGemFireNativeClient10.0.5

IssuesResolvedinGemFireNativeClient10.0.4

IssuesResolvedinGemFireNativeClient10.0.3

IssuesResolvedinGemFireNativeClient10.0.2

IssuesResolvedinGemFireNativeClient10.0.1

What’sNewinGemFireNativeClient10.0GemFireNativeClient10isbasedonApacheGeode1.8.Version10isamajorreleasethatintroducesimprovementsandseveralnewfeatures,someofwhichconstitutebreakingchangeswithregardtoversion9.

PivotalGemFireNativeClientimprovementsandnewfeaturesinclude:

AmodernizedC++APIthatconstitutesabigstepforwardtofullysupportingC++11.

Localmemorymanagementhasbeengreatlyimproved,aswellastheadoptionofanewcachemodelthatallowsformultiplecacheobjectstoexistinagivenprocessspace.

The.NETinterfacebenefitsfromalltheenhancementsmadeintheC++interface.

TheNativeClientnowsupportsIISapplicationdomainsandPivotalCloudFoundry.

Anewarchitecturethatallowsformoreflexibleclient-sidedatamodels

Improvementstothereflection-basedAutoSerializer

UpgradingaNativeClientApplicationFromVersion9toVersion10,provideshelpwiththeupgradefromNativeClient9.xtoNativeClient10.x.

TheApacheGeodecommunityhasahostofexamplesbasedonthelatestC++and.NETAPIs(https://github.com/apache/geode-native/tree/develop/examples ).

IssuesResolvedinGemFireNativeClient10.0.5GemFireNativeClientv10.0.5isapatchreleaseforGemFirev10.0customersthatincorporatesthefollowingbugfix:

©CopyrightPivotalSoftwareInc,2013-2019 4 10.0

Page 5: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

GEODE-8053:Fixedashutdownhang.Thestatistics-gatheringsystem’sStatsManagernolongerattemptstorunonaclosed,butnotyetdestroyed,Cacheinstance.

IssuesResolvedinGemFireNativeClient10.0.4GemFireNativeClientv10.0.4isapatchreleaseforGemFirev10.0customersthatincorporatesthefollowingbugfix:

GEODE-8015,GEMNC-470:Addeddebuggingsymbolstothereleasedlibraries.TheNativeClientreleaseforWindowsnowincludesa.pdbsymbolfile.OnLinux,thesymbolsarenowembeddedinthesharedlibrary(.sofile).

Note:TheGemFireNativeClient10.0.4buildwasinvalidduetopipelineissuesandhasbeenremoved.Pleasedownload10.0.5instead.

IssuesResolvedinGemFireNativeClient10.0.3GemFireNativeClientv10.0.3isapatchreleaseforGemFirev10.0customersthatincorporatesthefollowingbugfix:

GEODE-7511:IncreasedthebuffersizeforDNSnamestofixabugthatpresentedasthefailureofanapptoconnecttoacluster.

IssuesResolvedinGemFireNativeClient10.0.2GemFireNativeClientv10.0.2isapatchreleaseforGemFirev10.0customersthatincorporatesthefollowingbugfixes:

GEMNC-444:Addedsupportfora locators parameterin Web.config forthesessionstateprovider(.NETclientsonly).The locators parameterspecifiesaquotedstringcontaininglocator-name/port-numberpairs,separatedbycommas.

locators="locator-name1[port-number1],locator-name2[port-number2],..."

where:

locator-name canbeanumericIPaddressoraDNSnamesuchas“localhost”port-number isaportnumber

GEODE-6568:UseOpenSSLfromlocalinstall,supportOpenSSL1.0.1,1.0.2,1.1.0,and1.1.1.

©CopyrightPivotalSoftwareInc,2013-2019 5 10.0

Page 6: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

IssuesResolvedinGemFireNativeClient10.0.1GemFireNativeClientv10.0.1isapatchreleaseforGemFirev10.0customersthatincorporatesthefollowingbugfixes:

GEODE-6491:Fixsigned/unsignedproblemreadingsizefieldinhandshakemessage.

GEODE-6624:Improvedreportingofaserializationerrorthatpreviouslywasobscuredbyacrashduetonestedexceptions.

©CopyrightPivotalSoftwareInc,2013-2019 6 10.0

Page 7: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

SystemRequirementsInthistopic

GemFireCompatibility

.NETCompatibility

HostMachineRequirements

WindowsSupport

LinuxSupport

PCFSupport

SoftwareRequirementsforUsingSSL

ThePivotalGemFirenativeclientprovidesaccessforC++andMicrosoft®.NET™clientstotheGemFiredistributedsystem.ItoperatesonplatformsrunningMicrosoftWindows,Linux(Intel),andPivotalCloudFoundry.

GemFireCompatibilityTheGemFireNativeClientsupportsapplicationsthatcommunicatewithGemFireservers.NativeClientversion10.0workswithPivotalGemFireversions9.0.0andlater.

ThefollowingtableshowswhichversionsoftheNativeClientarecompatiblewiththevariousversionsoftheGemFireserver.

GemFireNativeClientVersion GemFireServerVersion

GemFireNativeClient10GemFireNativeClient9.1,9.2

GemFireServer9.x

GemFireNativeClient9.1GemFireNativeClient8.2

GemFireServer8.2

TheGemFireNativeClientsupportsapplicationsthatruninthefollowingclientenvironments:

SupportedPlatforms:C++Client

Platform Version

Linux RedHatEnterpriseLinux(RHEL)7

©CopyrightPivotalSoftwareInc,2013-2019 7 10.0

Page 8: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Linux Ubuntu16(Xenial)

WindowsDesktop 10

WindowsServer 2016

PivotalCloudFoundry PCF2.2+

Platform Version

SupportedPlatforms:.NETClient

Platform Version

WindowsDesktop 10

WindowsServer 2016

PivotalCloudFoundry PCF2.2+

.NETCompatibilityForWindowsapplications,aMicrosoft.NETFrameworkmustbeinstalledtosupporttheC++/CLI(CommonLanguageInfrastructure)libraryforthenativeclient.

Theclientsupports.NET4.5.2(andnewer)andVisualStudio2017(andnewer)(forcompiling.NETapplicationsonWindows).Itdoesnotsupport.NETCore.Formoreinformationonthefeaturesof.NETandVisualStudioCommunityEdition2017,seetheVisualStudio2017webpage .

HostMachineRequirementsEachmachinethatrunsanativeclientmustmeetthefollowingrequirements:

AsystemclocksettothecorrecttimeandatimesynchronizationservicesuchasNetworkTimeProtocol(NTP).Correcttimestampspermitthefollowingactivities:

Logsthatareusefulfortroubleshooting.Synchronizedtimestampsensurethatlogmessagesfromdifferenthostscanbemergedtoreproduceanaccuratechronologicalhistoryofadistributedrun.Aggregateproduct-levelandapplication-leveltimestatistics.Accuratemonitoringofthesystemwithscriptsandothertoolsthatreadthesystemstatisticsandlogfiles.

Thehostnameandhostfilesareproperlyconfiguredforthemachine.

©CopyrightPivotalSoftwareInc,2013-2019 8 10.0

Page 9: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

WindowsSupportForWindowsC++applications,theGemFireNativeClientlibrary, pivotal-gemfire.dll ,requirestheMicrosoftVisualC++2017RedistributablePackage .InstallitonallmachinesthatwillrunyourC++application.

LinuxSupportForLinux,youcanverifythatyoumeetthenativeclientdependenciesatthelibrarylevelbyusingtheldd toolandenteringthiscommand:

$ldd$client-installdir/lib/libpivotal-gemfire.so

whereclient-installdiristhelocationinwhichyouhaveinstalledtheclient.

Thefollowinglibrariesareexternaldependenciesofthenativelibrary, libpivotal-gemfire.so .Verifythattheldd tooloutputincludesallofthese:

libdl.so.2

libm.so.6

libpthread.so.0

libc.so.6

libz.so.1

DisablingSynCookiesonLinux

ManydefaultLinuxinstallationsuseSYNcookiestoprotectthesystemagainstmaliciousattacksthatfloodTCPSYNpackets.TheuseofSYNcookiesdramaticallyreducesnetworkbandwidth,andcanbetriggeredbyarunningGemFiredistributedsystem.

TodisableSYNcookiespermanently:

1. Editthe /etc/sysctl.conf filetoincludethefollowingline:

net.ipv4.tcp_syncookies=0

SettingthisvaluetozerodisablesSYNcookies.

2. Reload sysctl.conf :

©CopyrightPivotalSoftwareInc,2013-2019 9 10.0

Page 10: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

$sysctl-p

PCFSupportPivotalCloudFoundrysupports.NETandC++nativeclientapplications.

PCF.NETRequirements

PCF2.0ornewer

Windows2016

.NET4.5.2ornewer

Torunyourcloudnative.NETapplicationonPCF:

1. The Pivotal.GemFire.dll mustbeinthe output folderofyour.NETproject.

2. Add <hostingEnvironment shadowCopyBinAssemblies="false" /> tothe Web.Config .Thiswillchangethehostingbehaviortoreusetheexistingdirectory.

3. Rebuildyourapplication.

4. Use cf push todeployyourapplicationtoPCFasyouwouldother.NETapplications.

PCFC++Requirements

PCF2.0ornewer

UbuntuorWindows2016stemcells

TorunyourcloudnativeC++applicationonPCF:

1. Theruntimelibraries pivotal-gemfire.dll and cryptoImpl.dll mustbeinthepathofyourC++application.

2. Use cf push todeployyourapplicationtoPCFasyouwouldotherC++applications.

SoftwareRequirementsforUsingSSLIfyouplanonusingSSLinyourGemFirenativeclientandserverdeployment,youwillneedtodownload

©CopyrightPivotalSoftwareInc,2013-2019 10 10.0

Page 11: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

andinstallOpenSSL.TheGemFirenativeclientiscompatiblewithOpenSSLversions1.0.1,1.0.2,1.1.0,and1.1.1.

ForWindowsplatforms,youcanuseeithertheregularortheOpenSSL“Light”version.

Inaddition,makesurethatyoursystemenvironmentvariableshavebeenconfiguredtoincludeOpenSSL.

©CopyrightPivotalSoftwareInc,2013-2019 11 10.0

Page 12: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

UpgradingaNativeClientApplicationFromVersion9toVersion10GemFireNativeClientVersion10introducesbreakingchangesforVersion9applications.Updatingyourclientapplicationswillrequiremoreinterventionthanmerelyrecompiling.

Ingeneral,youwillhavebestperformanceandreliabilityifclientsandserversbothrunthelatestversionsoftheirrespectivesoftware.

GemFireserverandclientsoftwarereleasesfollowsimilarnumberingschemes,buttheyarenotreleasedinlockstep.ThefollowingdiagramillustratestheinteroperabilitybetweenrecentversionsofGemFireserversoftwareandGemFireNativeClientsoftware.

OverviewofChangesPivotalGemFireNativeClientimprovementsandnewfeaturesinclude:

AmodernizedC++APIthatconstitutesabigstepforwardtofullysupportingC++11.

Localmemorymanagementhasbeengreatlyimproved,aswellastheadoptionofanewcachemodelthatallowsformultiplecacheobjectstoexistinagivenprocessspace.

The.NETinterfacebenefitsfromalltheenhancementsmadeintheC++interface.

TheNativeClientnowsupportsIISapplicationdomainsandPivotalCloudFoundry.

Anewarchitecturethatallowsformoreflexibleclient-sidedatamodels

Improvementstothereflection-basedAutoSerializer

TheApacheGeodecommunityhasahostofexamplesbasedonthelatestC++and.NETAPIs(https://github.com/apache/geode-native/tree/develop/examples ).

ForexamplesofsourcechangesseetheNativeClient9toNativeClient10UpgradeSamples.

©CopyrightPivotalSoftwareInc,2013-2019 12 10.0

Page 13: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

C++Example

.NETExample

TheseexamplesshowboththeoriginalandnewAPIusage,andmaybehelpfulasstartingpointsforupgradingyourapplicationtoNativeClient10.ToseedetailsforupgradingyourparticularAPIusagerefertotheNativeClient10APIdocumentation:

C++APIdocs

.NETAPIdocs

CompilerUpgradeUsingVersion10oftheNativeClientwithyourapplicationrequiresaC++11-compatiblecompiler.

RemovalofCacheSingletonAmajorchangeinNativeClient10isthechangefromasingleton-baseddesigntoaninstance-baseddesign.Thisgivesdevelopersgreaterprogrammingflexibility,asclientcacheinstancescanhavecompletelyindependentaccesstotheGemFiredatagrid.

Multipleclient-sideinstancesofCachedonotautomaticallyshareobjectswithoneanother.

ThecachecreationprocessinNativeClient10followsadifferentpatternandnowreturnsanobject(seeexamples).Eachalsorequiresapool.NativeClient10furthersimplifiesthecachecreationandsystemarchitecturewiththeremovalof DistributedSystem .Aninstanceof DistributedSystem isnolongerneededtomanageanapplication’s“connecting”intotheGemFireJavaserver.ThisisnowmanagedthroughaCacheinstance.

Anoteto.NETusersoftheNativeClient:userscanpassinaninstanceoftheirauthorizationclassintothe

©CopyrightPivotalSoftwareInc,2013-2019 13 10.0

Page 14: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

CacheFactory( CacheFactory.SetAuthInitialize(app_auth); ).

SerializationInterfaceChangesTheNativeClientserializationAPIsforbothC++and.NEThavebeenchangedtomorecloselyresemblethebehavioroftheGemFireJavaclient.TheserializableAPIhasbeenrefactoredintodataserializableandPDXserializableinterfaces.Inaddition,tobeconsistentwiththeJavaServer,thenewdataserializableinterfacedoesnothavefixed ClassId properties. ClassId isnowaparameterpassedintoregisteragiventype.

C++StandardizationInNativeClient10,manyversion9utilityclasses,suchassharedpointers,havebeenreplacedbytheirequivalentsfromtheC++11standardlibrary.

OneofthebiggestchangesmadeinNativeClient10isthereplacementofcustomapache::geode::client::SharedPtr with std::shared_ptr .Thecustombaseobject apache::geode::client::SharedBase hasbeenremovedandisnolongerarequiredderivationtomakelibraryobjectsreferencecounted;insteadobjectsmaysimplybewrappedbya std::shared_ptr<> .UpgradingtoNativeClient10requiresreplacingall*PtrtypeswiththeirC++11replacements.

Forexample,replace

RegionPtrregionPtr;

with

std::shared_ptr<Region>regionPtr;

OtheradoptedC++11standardsinclude:

Alltimevaluesnowusestd::chrono.Forexample, std::chrono replaces CacheableDate

Longsandintsarenowreplacedwithlanguageprimitivesofexplicitsize,suchas int32_t andint16_t .

std:string replaces char *

stdcontainerclasses

PDXSerializable::objectSize() and DataSerializable::objectSize() return size_t

©CopyrightPivotalSoftwareInc,2013-2019 14 10.0

Page 15: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Propertiesuse std::unordered map

EnumClassesThefollowingVersion9EnumsarenowdefinedasC++11EnumclassesintheVersion10client:

CqOperation

CqState

ExpirationAction

PdxFieldTypes

ExceptionsGemFireNativeClientExceptions,whichwereimplementedasmacrosinv9,arenowclassesthatinheritfrom std::exception .

ObjectOrientedDesignPatternsNativeClient10hasadoptedmanymoreobjectorienteddesignpatterns.Forexample,the CacheFactorynowusesabuilderpatternandreturnsavalueratherthanapointer.

Otherexamplesofpattern-orientedchanges:

Replace apache::geode::client::PoolPtr withstd::shared_ptr<apache::geode::client::Pool>

Replace apache::geode::client::RegionPtr withstd::shared_ptr<apache::geode::client::Region>

Replace apache::geode::client::EntryEventPtr withstd::shared_ptr<apache::geode::client::EntryEvent>

Replace apache::geode::client::CachePtr withstd::unique_ptr<apache::geode::client::Cache>

PdxSerializabletoData/fromDataarenowpassedtoPdxWriter/PdxReaderasreferences

Executionfactoryreturnsvaluetype

Cache::createPdxInstanceFactory returnsobject

CqQuery::getCqAttributesMutator returnsvalue

©CopyrightPivotalSoftwareInc,2013-2019 15 10.0

Page 16: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Cache::createDataInput/Output returnsvalue

InitializationFilesThebestpracticeformostapplicationsistosetpropertiesandparametersprogrammatically.Forclientsthatusetheolder,file-basedscheme,thefollowingchangesapplytothesysteminitializationfiles,geode.properties and cache.xml :

Inbothfiles,parametersspecifyingtimesshouldincludeunits( s , m , h ,etc.).

Forthe cache.xml file,theschemanamespaceandlocationhavechanged.Use

<client-cachexmlns="http://geode.apache.org/schema/cpp-cache"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://geode.apache.org/schema/cpp-cachehttp://geode.apache.org/schema/cpp-cache/cpp-cache-1.0.xsd"version="1.0">

OtherChangesThe $GFCPP environmentvariableisnolongerneeded

enable-chunk-handler-thread nowdefaultsto false andreplacesdisable-chunk-handler-thread

NativeClient10nowsupportsOpenSSL

StatisticsandStatisticsFactoryarenolongeravailable

.NETAPIChangesThese.NETAPIclasseshavechangedasfollows:

CacheFactory

Creationwasviastaticmethod CreateCacheFactory ,nowcreatedvia new

Authorizationimplementationnowisasetteronfactorycalled SetAuthInitialize

Appdomain propertyisnolongerasupportedproperty

GetAnyInstance() isnolongersupported(thereisnomoreglobalsingleton).Makemethodcallsonthespecificinstanceyouareworkingwith

©CopyrightPivotalSoftwareInc,2013-2019 16 10.0

Page 17: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

PoolFactory

Creationwasobtainedviastaticmethod PoolManager.CreateFactory ,nowvia GetPoolFactorymethodon Cache

SetEntryTimeToLive -was int ,nowuses TimeSpan

SetEntryIdleTimeout-was int ,nowuses TimeSpan

SetRegionTimeToLive-was int ,nowuses TimeSpan

SetRegionIdleTimeout-was int ,nowuses TimeSpan

RegionFactory

SetEntryTimeToLive -was int ,nowuses TimeSpan .

IGeodeSerializable

The IGeodeSerializable interfacehasbeenrenamedto IDataSerializable .

.NETSessionStateProviderTheNativeClient10versionoftheSessionStateProvider(SSP)onlyrequiresconfigurationtobesetinWeb.Config andthedeploymentofserver-sidefunctions.

C++APIChangesThefollowingclasseshavechangedorarenolongerpresentinthecurrentrelease.

Version9:RemovedClass Version10:RecommendedAction

Assert N/A

AttributesFactory ReplacewithRegionAttributesFactory

CacheableArrayType,CacheableContainerType,CacheableKeyType

Convertedtotemplates.SeeINSTALL_DIR/include/geode/CacheableBuiltins.hpp

DistributedSystem Usedinternally

EqualToSB Nolongerneeded;usestdtypes

GeodeTypeIds RemovedfrompublicAPI

HashMapOfCacheable Replacewithstd::hash

©CopyrightPivotalSoftwareInc,2013-2019 17 10.0

Page 18: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

HashMapOfSharedBase Replacewithstd::hash

HashSB Replacewithstd::hash

HashSetOfCacheableKey Replacewithstd::hash

HashSetOfSharedBase Replacewithstd::shared_ptr<T>

HashSetT Replacewithstd::hash

InternalCacheTransactionManager2PC RemovedfrompublicAPI

Log UseLogLevelatcachecreation

LogFn UseLogLevelatcachecreation

LogVarargs UseLogLevelatcachecreation

NullSharedBase Replacewithnullptr

SelectResultsIterator ReplacewithResultsCollector

SharedArrayPtr Replacewithstd::shared_ptr<T>

SharedBaseAbstractbaseclassnolongerneeded.Replacewithstd::shared_ptr<T>

SharedPtr Replacewithstd::shared_ptr<T>

SPEHelperExceptionhelpernolongerneededaftermovefromSharedPtrtostd::shared_ptr

VectorOfCacheable std::vector<std::shared_ptr<T>>

VectorOfCacheableKey std::vector<std::shared_ptr<T>>

VectorOfSharedBase std::vector<std::shared_ptr<T>>

VectorT std::vector<T>

Version9:RemovedClass Version10:RecommendedAction

Thefollowingclasseshavechangedornewinthecurrentrelease.

NeworRenamedClass SummaryofChanges

AuthenticatedView ReplacesAuthenticatedCacheinv9API.Usedformulti-userauthentication.

DataSerializableAninterfaceforobjectswhosestatecanbewritten/readasprimitivetypes.SupersedesSerializable,whichisnowthesuperclassofalluserobjectsinthecachethatcanbeserialized.

DefaultResultCollectorDefaultclassthatgathersresultsfromfunctionexecution.TheResultCollectorinterfacealsochanged.

LogLevel Methodreturnsloglevel.

©CopyrightPivotalSoftwareInc,2013-2019 18 10.0

Page 19: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

RegionAttributesFactory ReplacedwithAttributesFactory

RegionShortcutEnumclassholdingallregiontypes(PROXY,CACHING_PROXY,CACHING_PROXY_ENTRY_LRU,LOCAL_ENTRY_LRU)

TypeRegistry Classforregisteringacustomserializabletype.

NeworRenamedClass SummaryofChanges

©CopyrightPivotalSoftwareInc,2013-2019 19 10.0

Page 20: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

InstallingtheNativeLibraryInstallthenativeclientbyextractingthecontentsofthedistributionarchiveandsettinguptheenvironment.

InstallationPrerequisites

BeforeinstallingtheGemFirenativeclient,confirmthatyoursystemmeetsthehardwareandsoftwarerequirementsdescribedinGemFireNativeClientSystemRequirements.

CopyandUncompresstheDistributionArchive

1. Inabrowser,navigatetothePivotalGemFiredownloadpage .

2. FromtheReleases:pull-downmenu,selectthemostrecentversionofPivotalGemFireNativeClient.

3. ExpandtheentryintheReleaseDownloadFilesdialogbox,selecttheversionthatbestsuitsyourdevelopmentplatform,anddownloadit.

4. MovethedownloadedarchivetothelocaldirectoryorfolderinwhichyouwishtoinstalltheNativeClientlibraries.Foreaseofuse,chooseawell-knownlocation:

OnLinux,/usr/localOnWindows,C:\ProgramFiles

5. Uncompressthedistributionarchive,whichmaybeaZIParchiveoracompressedtarfile(.tar.gzor.tgz).Forexample:

$unzippivotal-gemfire-nativeclient-windows-64bit-10.x.y.zip

or

$tarxvzfpivotal-gemfire-nativeclient-linux-64bit-10.x.y.tar.gz

6. Foreaseofuse,renametheresultingdirectoryto nativeclient .

©CopyrightPivotalSoftwareInc,2013-2019 20 10.0

Page 21: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

GettingStartedwiththeNativeLibraryInthistopic

SetUpYourDevelopmentEnvironment

EstablishAccesstoaGemFireClusterConnectingtotheServer

ApplicationDevelopmentWalkthroughs

ProgrammingExamples

TousetheGemFireNativeLibraryfordevelopingGemFireclientapplications:

ObtainadistributionoftheNativelibraryandinstallitonyourdevelopmentplatform.

Setupyourdevelopmentenvironmentwiththetoolsyouneed,suchasacompilerandanOpenSSLsecuritylibrary.

EstablishaccesstoaneworexistingGemFirecluster.

WriteyourclientapplicationusingtheGemFirenativelibrarytointeractwiththeGemFireserver.

SetUpYourDevelopmentEnvironmentWhetheryouaredevelopingaC++or.NETapplication,youwillneedsomeessentialtools,suchasacompilerandalinker.YourcompilermusthaveaccesstotheNativeClientheaderfiles,andthelinkermusthaveaccesstotheNativeClientlibraries.TheheaderfilesandlibrariesarelocatedintheNativeClientinstallationdirectory.

EstablishAccesstoaGemFireClusterAsyoudevelopyourapplication,youwillneedaccesstoaGemFirecluster.YourclientapplicationconnectstoaGemFireclusterbyspecifyingtheaddress(hostnameorIPaddress)andportnumberofoneormorelocators,andthenameofaregionthatalsoexistsonthecluster.TheclientAPIestablishesapoolofthesenetworkconnectionsforyourclientapplicationtouse.

Youcanchoosewhethertousealarge,remote,production-qualitycluster;asmall,local,developmentcluster;orsomethingin-between,suchasatestingorexperimentallabinstallation.

IntheGemFireUser’sGuide,seeConfiguringandRunningaCluster andClient/ServerConfiguration forinstructionsonsettingupandstartingtheclusterforaclient/serverconfiguration.

ConnectingtotheServer

Toconnecttoaserver,yourapplicationmustfollowthesesteps:

1. Instantiatea CacheFactory ,settingcharacteristicsofinterest(forexample, log-level ).

©CopyrightPivotalSoftwareInc,2013-2019 21 10.0

Page 22: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

2. Createacacheanduseittoinstantiatea PoolFactory ,specifyingthehostnameandportfortheserverlocator.

3. Createanamedpoolofnetworkconnections.

4. Instantiatearegionofthedesiredtype(usuallyCACHING_PROXYorPROXY)andconnectitbynametoitscounterpartontheserver.

Oncetheconnectionpoolandthesharedregionareinplace,yourclientapplicationisreadytosharedatawiththeserver.

ServerConnection:C++Example

ThisexampleofconnectingtotheserveristakenfromtheC++ put-get-remove example.

Instantiatea CacheFactory andsetitscharacteristics:

autocacheFactory=CacheFactory();//instantiatecachefactorycacheFactory.set("log-level","none");//setcachelog-levelcharacteristics

Createacacheanduseittoinstantiatea PoolFactory :

autocache=cacheFactory.create();//createcacheautopoolFactory=cache.getPoolManager().createFactory();//instantiatepoolfactory

poolFactory.addLocator("localhost",10334);//addlocatortopoolfactory

Createanamedpoolofnetworkconnections,andinstantiatearegionofthedesiredtype:

autopool=poolFactory.create("pool");//createapoolcalled"pool"thatknowswheretheserverisautoregionFactory=cache.createRegionFactory(RegionShortcut::PROXY);//instantiateregionfactorywithPROXYcharacteristicsautoregion=regionFactory.setPoolName("pool").create("example_userinfo");//createaconnectiontotheregion"example_userinfo"ontheserver

ServerConnection:.NETExample

Thisexampleofconnectingtotheserveristakenfromthe.NET PutGetRemove example.

Instantiatea CacheFactory andsetitscharacteristics:

varcacheFactory=newCacheFactory()//instantiatecachefactory.Set("log-level","none");//setcachelog-levelcharacteristics

Createacacheanduseittoinstantiatea PoolFactory :

varcache=cacheFactory.Create();//createcache

varpoolFactory=cache.GetPoolFactory()//instantiatepoolfactory.AddLocator("localhost",10334);//addlocatortopoolfactory

©CopyrightPivotalSoftwareInc,2013-2019 22 10.0

Page 23: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Createanamedpoolofnetworkconnections,andinstantiatearegionofthedesiredtype:

poolFactory.Create("pool");//createapoolcalled"pool"thatknowswheretheserveris

varregionFactory=cache.CreateRegionFactory(RegionShortcut.PROXY)//instantiateregionfactorywithPROXYcharacteristics.SetPoolName("pool");varregion=regionFactory.Create<string,string>("example_userinfo");//createaconnectiontotheregion"example_userinfo"ontheserver

SeetheGemFireUserGuidesectionConfiguringaClient/ServerSystem formoredetails.

ApplicationDevelopmentWalkthroughs

TheapplicationdevelopmentwalkthroughsdescribehowtosetupanativeclientdevelopmentenvironmentusingCMake.

C++AppDevelopmentWalkthrough

.NETAppDevelopmentWalkthrough

ProgrammingExamplesTheGemFireClientbuildprovidesasetofprogrammingexamplestohelpyouunderstandtheclientAPI.The examples

directorycontainsCMakefilesanda cpp subdirectorycontainingC++examples.TheWindowsbuildalsoincludesadotnet subdirectorycontainingC#examples.

CMakefilesarelocatedateachlevelofthedirectorystructuretoallowexamplestobebuiltindividuallyoringroups.

Thedirectorystructureresemblesthishierarchy(someentriesareomittedforclarity):

©CopyrightPivotalSoftwareInc,2013-2019 23 10.0

Page 24: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

MyProject/cmake/CMakeLists.txtexamples/BUILD-EXAMPLES.mdCMakeLists.txtCMakeLists.txt.incmake/cpp/authinitialize/continuousquery/dataserializable/functionexecution/pdxserializable/pdxserializer/putgetremove/remotequery/sslputget/transaction/dotnet/authinitialize/continuousquery/dataserializable/functionexecution/pdxautoserializer/pdxserializable/putgetremove/remotequery/sslputget/transaction/

Seethe BUILD-EXAMPLES.md filefordetailedinstructionsonbuildingandexecutingtheexamples,andreadthesourcecodetounderstandhowtheexamplesareconstructed.

SeePut/Get/RemoveExamplesforsamplecodeshowingthebasicsofhowaclientapplicationconnectstoaGemFireclusterandperformsbasicoperationsonaremoteserver.

©CopyrightPivotalSoftwareInc,2013-2019 24 10.0

Page 25: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Put/Get/RemoveExamplesInthistopic

.NETExample

C++Example

Thenativeclientreleasecontainsexamples,writtenfor.NETandC++,showinghowaclientapplicationcanestablishaconnectiontoaclusterandthenusethatconnectiontoperformbasicoperationsonaremoteserver.Theexamplesarelocatedin ../examples/dotnet/putgetremove and ../examples/cpp/putgetremove ,respectively.

Bothexamplesperformthesamesequenceofoperations,displayingsimplelogentriesastheyrun.

Torunanexample,followtheinstructionsinthe README.md fileintheexampledirectory.

Reviewthesourcecodeintheexampledirectorytoseeexactlyhowitoperates.

Beginbyrunningascriptthatsetsuptheserver-sideenvironmentbyinvoking gfsh commandstocreatearegion,simplycalled“example_userinfo.”

Runtheexampleclientapplication,whichperformsthefollowingsteps:

ConnectstotheserverPerformsregionputoperationsusingkey/valuepairsUsesregiongettoretrievethevaluesUsesregionremovetoremovethevalues

.NETExampleThissectioncontainscodesnippetsshowinghighlightsofthe.NETput/get/removeexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.

The.NETexamplecreatesacache,thenusesittocreateaconnectionpoolandaregionobject(ofclassIRegion ).

©CopyrightPivotalSoftwareInc,2013-2019 25 10.0

Page 26: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

varcacheFactory=newCacheFactory().Set("log-level","none");varcache=cacheFactory.Create();

varpoolFactory=cache.GetPoolFactory().AddLocator("localhost",10334);poolFactory.Create("pool");

varregionFactory=cache.CreateRegionFactory(RegionShortcut.PROXY).SetPoolName("pool");varregion=regionFactory.Create<string,string("example_userinfo");

Afterdeclaringsomekeysandvalues,theclientthenpopulatesthedatastorewithtwokey/valuepairs.

region.Put(rtimmonsKey,rtimmonsValue);region.Put(scharlesKey,scharlesValue);

Next,theapplicationretrievesthestoredvaluesusing Get operations.

varuser1=region.Get(rtimmonsKey,null);varuser2=region.Get(scharlesKey,null);

Finally,theapplicationdeletesoneofthestoredvaluesusingthe Remove method.

if(region.Remove(rtimmonsKey)){Console.WriteLine("Infofor"+rtimmonsKey+"hasbeendeleted");}else{Console.WriteLine("Infofor"+rtimmonsKey+"hasnotbeendeleted");}

C++ExampleThissectioncontainscodesnippetsshowinghighlightsoftheC++put/get/removeexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.

TheC++examplecreatesacache,thenusesittocreateaconnectionpoolandaregionobject(ofclassRegion ).

©CopyrightPivotalSoftwareInc,2013-2019 26 10.0

Page 27: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

autocacheFactory=CacheFactory();cacheFactory.set("log-level","none");autocache=cacheFactory.create();autopoolFactory=cache.getPoolManager().createFactory();

poolFactory.addLocator("localhost",10334);autopool=poolFactory.create("pool");autoregionFactory=cache.createRegionFactory(RegionShortcut::PROXY);autoregion=regionFactory.setPoolName("pool").create("example_userinfo");

Theclientthenpopulatesthedatastorewithtwokey/valuepairs.

region->put("rtimmons","RobertTimmons");region->put("scharles","SylviaCharles");

Next,theapplicationretrievesthestoredvaluesusing Get operations.

autouser1=region->get("rtimmons");autouser2=region->get("scharles");

Finally,theapplicationdeletesoneofthestoredvaluesusingthe Remove method.

if(region->existsValue("rtimmons")){std::cout<<"rtimmons'sinfonotdeleted"<<std::endl;}else{std::cout<<"rtimmons'sinfosuccessfullydeleted"<<std::endl;}

©CopyrightPivotalSoftwareInc,2013-2019 27 10.0

Page 28: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

ConfiguringaClientApplicationInthistopic

ProgrammaticConfigurationvsXMLConfiguration

HighAvailabilitywithServerRedundancy

Youcanconfigureyournativeclientapplication:

Programmaticallyinyourappcode

ViaXMLfilesandpropertiesfiles(seeClientCacheXMLReference)

Throughacombinationofprogrammaticandfile-basedapproaches

Thissectiondescribesconfigurationontwolevels,thesystemlevelandthecachelevel.Systempropertysettingsdescribeyourapplication’sbehavior,whilecacheconfigurationdescribesdata.

ProgrammaticConfigurationvsXMLConfigurationProgrammaticconfigurationenablesyourclientapplicationtodynamicallyadapttochangingruntimeconditions.

Incontrast,XMLconfigurationexternalizesproperties,suchaslocatoraddressesandpoolconnectiondetails,sotheycanbechangedwithoutrequiringthatyourecompileyourapplication.

C++RegionFactoryExample

Thefollowingexamplesillustratehowtosetaregion’sexpirationtimeoutattributeprogrammaticallyandthroughXML.

Settingapropertyprogrammatically:

autoregionFactory=cache.createRegionFactory(RegionShortcut::CACHING_PROXY);autoregion=regionFactory.setRegionTimeToLive(ExpirationAction::INVALIDATE,std::chrono::seconds(120)).create("exampleRegion0");

XMLequivalent:

©CopyrightPivotalSoftwareInc,2013-2019 28 10.0

Page 29: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<regionname="exampleRegion0"refid="CACHING_PROXY"><region-attributespool-name="default"><region-time-to-live><expiration-attributestimeout="120s"action="invalidate"/></region-time-to-live></region-attributes></region>

TablesofpropertiesSeeSystemPropertiesforalistofsystempropertiesthatcanbeconfiguredprogrammaticallyorinthegeode.properties file.

HighAvailabilitywithServerRedundancyWhenredundancyisenabled,secondaryserversmaintainqueuebackupswhiletheprimaryserverpusheseventstotheclient.Iftheprimaryserverfails,oneofthesecondaryserversstepsinasprimarytoprovideuninterruptedeventmessagingtotheclient.Toconfigurehighavailability,setthesubscription-redundancy intheclient’spoolconfiguration.Thissettingindicatesthenumberofsecondaryserverstouse.SeetheGemFireUserGuidesectionConfiguringHighlyAvailableServers formoredetails.

©CopyrightPivotalSoftwareInc,2013-2019 29 10.0

Page 30: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

SystemLevelConfigurationInthistopic

AttributeDefinitionPriority

SearchPathforMultiplePropertiesFiles

DefiningPropertiesProgrammatically

Aboutthegeode.propertiesConfigurationFile

ConfigurationFileLocations

UsingtheDefaultSampleFile

ConfiguringSystemPropertiesfortheClient

RunningaClientOutoftheBox

AttributeDefinitionPriorityYoucanspecifyattributesindifferentways,whichcancauseconflictingdefinitions.Applicationscanbeconfiguredprogrammatically,andthathaspriorityoverothersettings.

Incaseanattributeisdefinedinmorethanoneplace,thefirstsourceinthislistisused:

Programmaticconfiguration

Propertiessetatthecommandline

current-working-directory/geode.properties file

native-client-installation-directory/defaultSystem/geode.properties file

defaults

The geode.properties filesandprogrammaticconfigurationareoptional.Iftheyarenotpresent,nowarningsorerrorsoccur.Fordetailsonprogrammaticconfigurationthroughthe Properties object,seeDefiningPropertiesProgrammatically.

SearchPathforMultiplePropertiesFilesTheclientandcacheserverprocessesfirstlookfortheirpropertiesfileinthenative-client-installation-directory/defaultSystem directory,thenintheworkingdirectory.

©CopyrightPivotalSoftwareInc,2013-2019 30 10.0

Page 31: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Anypropertiessetintheworkingdirectoryoverridesettingsinthenative-client-installation-directory/defaultSystem/geode.properties file.

The geode.properties fileprovidesinformationtotheclientregardingtheexpectedserverconfiguration.Propertiessetinthisfile(intheclientenvironment)donothaveanyeffectontheserveritself.Itsmainpurposeistoinformtheclientapplicationastohowtocommunicatewiththeserver.

DefiningPropertiesProgrammaticallyYoucanpassinspecificpropertiesprogrammaticallybyusinga Properties objecttodefinethenon-defaultproperties.

Example:

autosystemProps=Properties::create();systemProps->insert("statistic-archive-file","stats.gfs");systemProps->insert("cache-xml-file","./myapp-cache.xml");systemProps->insert("stacktrace-enabled","true");autocache=CacheFactory(systemProps).create();

Aboutthegeode.propertiesConfigurationFileThe geode.properties fileprovideslocalsettingsrequiredtoconnectaclienttoadistributedsystem,alongwithsettingsforlicensing,logging,andstatistics.SeeSystemProperties.

ConfigurationFileLocationsAclientlooksfora geode.properties filefirstintheworkingdirectorywheretheprocessruns,theninnative-client-installation-directory/defaultSystem .Usethe defaultSystem directorytogroupconfigurationfilesortosharethemamongprocessesformoreconvenientadministration.If geode.properties isnotfound,theprocessstartsupwiththedefaultsettings.

Forthe cache.xml cacheconfigurationfile,aclientlooksforthepathspecifiedbythe cache-xml-file

attributein geode.properties (seeSystemProperties).Ifthe cache.xml isnotfound,theprocessstartswithanunconfiguredcache.

UsingtheDefaultSampleFile

©CopyrightPivotalSoftwareInc,2013-2019 31 10.0

Page 32: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Asample geode.properties fileisincludedwiththePivotalGemFirenativeclientinstallationinthenative-client-installation-directory/defaultSystem directory.

Tousethisfile:

1. Copythefiletothedirectorywhereyoustarttheapplication.

2. Uncommentthelinesyouneedandeditthesettingsasshowninthisexample:

cache-xml-file=test.xml

3. Starttheapplication.

Defaultgeode.propertiesFile

#DefaultC++distributedsystemproperties#Copytocurrentdirectoryanduncommenttooverridedefaults.###Debuggingsupport,enablesstacktracesinapache::geode::client::Exception.##Thedefaultisfalse,uncommenttoenablestacktracesinexceptions.#stacktrace-enabled=true#crash-dump-enabled=true####Cacheregionconfiguration##cache-xml-file=cache.xml###Logfileconfig##log-file=gemfire_cpp.log#log-level=config#zeroindicatesusenolimit.#log-file-size-limit=0#zeroindicatesusenolimit.#log-disk-space-limit=0...

ConfiguringSystemPropertiesfortheClientThetypicalconfigurationprocedureforaclientincludesthehigh-levelstepslistedbelow.

1. Placethe geode.properties filefortheapplicationintheworkingdirectoryorin

©CopyrightPivotalSoftwareInc,2013-2019 32 10.0

Page 33: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

native-client-installation-directory/defaultSystem .

2. Placethe cache.xml filefortheapplicationinthedesiredlocationandspecifyitspathusingthecache-xml-file propertyinthe geode.properties file.

3. Addotherattributestothe geode.properties fileasneededforthelocalsystemarchitecture.

RunningaClientOutoftheBoxIfyoustartaclientwithoutanyconfiguration,itusesanyattributessetprogrammaticallyplusanyhard-codeddefaults(listedinSystemProperties).Runningwiththedefaultsisaconvenientwaytolearntheoperationofthedistributedsystemandtotestwhichattributesneedtobereconfiguredforyourenvironment.

Runningbasedondefaultsisnotrecommendedforproductionsystems,asimportantcomponents,suchassecurity,mightbeoverlooked.

©CopyrightPivotalSoftwareInc,2013-2019 33 10.0

Page 34: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

ConfiguringtheClientCacheClientcachesprovidetheframeworkforclientstostore,manage,anddistributeapplicationdata.

AcacheisanentrypointforaccesstoGemFire.Throughthecache,clientsgainaccesstotheGemFirecachingframeworkfordataloading,distribution,andmaintenance.

A Cache instanceallowsyourclienttosetgeneralparametersforcommunicationbetweenacacheandothercachesinthedistributedsystem,andtocreateandaccessanyregioninthecache.

Regionsarecreatedfrom Cache instances.Regionsprovidetheentrypointstotheinterfacesforinstancesof Region and RegionEntry .

Formoreinformationspecifictoyourclientprogramminglanguage,seetheC++ClientAPI orthe.NETClientAPI .

©CopyrightPivotalSoftwareInc,2013-2019 34 10.0

Page 35: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

ConfiguringRegionsInthistopic

ProgrammaticRegionCreation

DeclarativeRegionCreation

InvalidatingandDestroyingRegions

RegionAccess

GettingtheRegionSize

TheregionisthecorebuildingblockoftheGemFiredistributedsystem.Allcacheddataisorganizedintodataregionsandyoudoallofyourdataputs,gets,andqueryingactivitiesagainstthem.

InordertoconnecttoaGemFireserver,aclientapplicationmustdefinearegionthatcorrespondstoaregionontheserver,atleastinname.SeeDataRegions intheGemFireUserGuidefordetailsregardingserverregions,andRegionAttributesinthisguideforclientregionconfigurationparameters.

Youcancreateregionseitherprogrammaticallyorthroughdeclarativestatementsina cache.xml file.Programmaticconfigurationisrecommended,asitkeepstheconfigurationcloseathandandeliminatesanexternaldependency.Regioncreationissubjecttoattributeconsistencychecks.

ProgrammaticRegionCreationTocreatearegion:

1. Instantiatea CacheFactory anduseittocreateacache.

2. Thecacheincludesaninstanceof PoolManager —useittocreateaconnectionpool.

3. Usecachetoinstantiatea RegionFactory anduseittocreatearegion,specifyinganydesiredattributesandanassociationwiththeconnectionpool.

C++RegionCreationExample

ThefollowingexampleillustrateshowtocreatetworegionsusingC++.

©CopyrightPivotalSoftwareInc,2013-2019 35 10.0

Page 36: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

autocache=CacheFactory().create();

autoexamplePool=cache.getPoolManager().createFactory().addLocator("localhost",40404).setSubscriptionEnabled(true).create("examplePool");

autoclientRegion1=cache.createRegionFactory(RegionShortcut::PROXY).setPoolName("examplePool").create("clientRegion1");

.NETC#RegionCreationExample

ThisexampleillustrateshowtocreateapairofregionsusingC#:

varcache=newCacheFactory().Create();

varexamplePool=cache.GetPoolManager().CreateFactory().AddLocator("localhost",40404).SetSubscriptionEnabled(true).Create("examplePool");

varclientRegion1=cache.CreateRegionFactory(RegionShortcut.PROXY).SetPoolName("examplePool").Create("clientRegion1");

DeclarativeRegionCreationDeclarativeregioncreationinvolvesplacingtheregion’sXMLdeclaration,withtheappropriateattributesettings,ina cache.xml filethatisloadedatcachecreation.

Liketheprogrammaticexamplesabove,thefollowingexamplecreatestworegionswithattributesandaconnectionpool:

©CopyrightPivotalSoftwareInc,2013-2019 36 10.0

Page 37: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<?xmlversion="1.0"encoding="UTF-8"?><client-cachexmlns="http://geode.apache.org/schema/cpp-cache"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://geode.apache.org/schema/cpp-cachehttp://geode.apache.org/schema/cpp-cache/cpp-cache-1.0.xsd"version="1.0"><poolname="examplePool"subscription-enabled="true"><serverhost="localhost"port="40404"/></pool><regionname="clientRegion1"refid="PROXY"><region-attributespool-name="examplePool"/></region><regionname="clientRegion2"refid="CACHING_PROXY"><region-attributespool-name="examplePool"><region-time-to-live><expiration-attributestimeout="120s"action="invalidate"/></region-time-to-live></region-attributes></region></client-cache>

The cache.xml filecontentsmustconformtotheXMLdescribedinthe cpp-cache-1.0.xsd fileprovidedinyourdistribution’s xsds subdirectoryandavailableonlineathttps://geode.apache.org/schema/cpp-cache/cpp-cache-1.0.xsd .

InvalidatingandDestroyingRegionsInvalidationmarksallentriescontainedintheregionasinvalid(withnullvalues).Destructionremovestheregionandallofitscontentsfromthecache.

Youcanexecutetheseoperationsexplicitlyinthelocalcacheinthefollowingways:

ThroughdirectAPIcallsfromtheclient.

.NET:Apache::Geode::Client::IRegion::InvalidateRegion()C++:apache::geode::client::Region:invalidateRegion()

Throughexpirationactivitiesbasedontheregion’sstatisticsandattributesettings.

Ineithercase,youcanperforminvalidationanddestructionasalocaloradistributedoperation.

Alocaloperationaffectstheregiononlyinthelocalcache.

Adistributedoperationworksfirstontheregioninthelocalcacheandthendistributestheoperation

©CopyrightPivotalSoftwareInc,2013-2019 37 10.0

Page 38: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

toallothercacheswheretheregionisdefined.Thisistheproperchoicewhentheregionisnolongerneeded,orvalid,foranyapplicationinthedistributedsystem.

Iftheregionontheserverisconfiguredasapartitionedregion,itcannotbeclearedusingAPIcallsfromtheclient.

Auser-definedcachewritercanabortaregiondestroyoperation.Cachewritersaresynchronouslistenerswiththeabilitytoabortoperations.Ifacachewriterisdefinedfortheregionanywhereinthedistributedsystem,itisinvokedbeforetheregionisexplicitlydestroyed.

Whethercarriedoutexplicitlyorthroughexpirationactivities,invalidationanddestructioncauseeventnotification.

RegionAccessYoucanuse Cache::getRegion toretrieveareferencetoaspecifiedregion.

Cache::getRegion returns nullptr iftheregionisnotalreadypresentintheapplication’scache.Aserverregionmustalreadyexist.

Aregionnamecannotcontainthesecharacters:

IneligibleCharacterdescription IneligibleCharacter

whitespace spaceortab

anglebrackets <>

colon :

quote "

forwardslashandbackslash /\

pipe(verticalbar) |

questionmark ?

asterisk *

GettingtheRegionSizeThe Region APIprovidesa size method( Size propertyfor.NET)thatgetsthesizeofaregion.Forclientregions,thisgivesthenumberofentriesinthelocalcache,notontheservers.Seethe Region APIdocumentationfordetails.

©CopyrightPivotalSoftwareInc,2013-2019 38 10.0

Page 39: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

©CopyrightPivotalSoftwareInc,2013-2019 39 10.0

Page 40: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

RegisteringInterestforEntriesForclientregions,youcanprogrammaticallyregisterinterestinentrykeysstoredonacacheserverregion.Aclientregionreceivesupdatenotificationsfromthecacheserverforthekeysofinterest.

Youcanregisterinterestforspecificentrykeysorforallkeys.Regularexpressionscanbeusedtoregisterinterestforkeyswhosestringsmatchtheexpression.Youcanalsounregisterinterestforspecifickeys,groupsofkeysbasedonregularexpressions,orforallkeys.

Note:Interestregistrationandunregistrationaresymmetricaloperations.Consequently,youcannotregisterinterestinallkeysandthenunregisterinterestinaspecificsetofkeys.Also,ifyoufirstregisterinterestinspecifickeyswith registerKeys ,thencall registerAllKeys ,youmustcall unregisterAllKeys beforespecifyinginterestinspecifickeysagain.

ClientAPIforRegisteringInterestYouregisterclientinterestthroughtheC++orNETAPI.TheC++APIprovidesthe registerKeys ,registerAllKeys ,and registerRegex methods,withcorrespondingunregistrationaccomplishedusingtheunregisterKeys , unregisterAllKeys ,and unregisterRegex methods.The.NETAPIprovidesthe RegisterKeys ,RegisterAllKeys ,and RegisterRegex methods,withcorrespondingunregistrationaccomplishedusingtheUnregisterKeys , UnregisterAllKeys ,and UnregisterRegex methods.

The registerKeys , registerRegex and registerAllKeys methodshavetheoptiontopopulatethecachewiththeregistrationresultsfromtheserver.The registerRegex and registerAllKeys methodscanalsooptionallyreturnthecurrentlistofkeysregisteredontheserver.

SettingUpClientNotificationInadditiontotheprogrammaticfunctioncalls,toregisterinterestforaserverregionandreceiveupdatedentriesyouneedtoconfiguretheregionwiththe PROXY or CACHING_PROXYRegionShortcut setting.Theregion’spoolshouldhave subscription-enabled=true seteitherintheclientXMLorprogrammaticallyviaaCacheFactory::setSubscriptionEnabled(true) APIcall.Otherwise,whenyouregisterinterest,youwillgetanUnsupportedOperationException .

<regionname="listenerWriterLoader"refid="CACHING_PROXY">...

Allclientsthathavesubscriptionsenabledtrackanddrop(ignore)anyduplicatenotificationsreceived.

©CopyrightPivotalSoftwareInc,2013-2019 40 10.0

Page 41: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Toreduceresourceusage,aclientexpirestrackedsourcesforwhichnewnotificationshavenotbeenreceivedforaconfigurableamountoftime.

NotificationSequence

Notificationsinvoke CacheListeners ofcachelessclientsinallcasesforkeysthathavebeenregisteredontheserver.Similarly,invalidatesreceivedfromtheserverinvoke CacheListeners ofcachelessclients.

Ifyouregistertoreceivenotifications,listenercallbacksareinvokedirrespectiveofwhetherthekeyisintheclientcachewhena destroy or invalidate eventisreceived.

RegisteringInterestforSpecificKeysYouregisterandunregisterinterestforspecifickeysthroughthe registerKeys and unregisterKeys

functions.Youregisterinterestinakeyorsetofkeysbyspecifyingthekeynameusingtheprogrammaticsyntaxshowninthefollowingexample:

keys0.push_back(keyPtr1);keys1.push_back(keyPtr3);regPtr0->registerKeys(keys0);regPtr1->registerKeys(keys1);

Theprogrammaticcodesnippetinthenextexampleshowshowtounregisterinterestinspecifickeys:

regPtr0->unregisterKeys(keys0);regPtr1->unregisterKeys(keys1);

RegisteringInterestforAllKeysIftheclientregistersinterestinallkeys,theserverprovidesnotificationsforallupdatestoallkeysintheregion.Thenextexampleshowshowtoregisterinterestinallkeys:

regPtr0->registerAllKeys();regPtr1->registerAllKeys();

Thefollowingexampleshowsacodesampleforunregisteringinterestinallkeys.

regPtr0->unregisterAllKeys();regPtr1->unregisterAllKeys();

©CopyrightPivotalSoftwareInc,2013-2019 41 10.0

Page 42: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

RegisteringInterestUsingRegularExpressionsThe registerRegex functionregistersinterestinaregularexpressionpattern.Theserverautomaticallysendstheclientchangesforentrieswhosekeysmatchthespecifiedpattern.

Keysmustbestringsinordertoregisterinterestusingregularexpressions.

Thefollowingexampleshowsinterestregistrationforallkeyswhosefirstfourcharactersare Key- ,followedbyanystringofcharacters.Thecharacters .* representawildcardthatmatchesanystring.

regPtr1->registerRegex("Key-.*");

Tounregisterinterestusingregularexpressions,youusethe unregisterRegex function.Thenextexampleshowshowtounregisterinterestinallkeyswhosefirstfourcharactersare Key- ,followedbyanystring(representedbythe .* wildcard).

regPtr1->unregisterRegex("Key-.*");

RegisterInterestScenarioInthisregisterinterestscenario,acachelistenerisusedwithacachelessregionthathassubscription-enabled setto true .Theclientregionisconfiguredwithcachingdisabled;clientnotificationisenabled;andacachelistenerisestablished.Theclienthasnotregisteredinterestinanykeys.

Whenavaluechangesinanotherclient,itsendstheeventtotheserver.Theserverwillnotsendtheeventtothecachelessclient,eventhough client-notification issetto true .

Toactivatethecachelistenersothecachelessregionreceivesupdates,theclientshouldexplicitlyregisterinterestinsomeorallkeysbyusingoneoftheAPIcallsforregisteringinterest.Thisway,theclientreceivesalleventsforthekeystowhichithasregisteredinterest.ThisappliestoJava-basedclientsaswellasnon-Javaclients.

©CopyrightPivotalSoftwareInc,2013-2019 42 10.0

Page 43: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

RegionAttributesRegionattributesgoverntheautomatedmanagementofaregionanditsentries.

Regionattributesettingsdeterminewherethedataresides,howtheregionismanagedinmemory,andtheautomaticloading,distribution,andexpirationofregionentries.

SpecifyingRegionAttributesSpecifyregionattributesbeforecreatingtheregion.YoucandothiseitherthroughtheAPIorthroughthedeclarativeXMLfile.TheAPIincludesclassesfordefiningaregion’sattributesbeforecreationandformodifyingsomeattributesaftercreation.Fordetails,seetheAPIfor RegionShortcut , RegionAttributes ,RegionAttributesFactory ,and AttributesMutator .

RegionShortcutsGemFireprovidespredefined,shortcutregionattributessettingsforyourusein RegionShortcut .Theshortcutsare:

PROXY

doesnotstoredataintheclientcache,butconnectstheregiontotheservers.

CACHING_PROXY

storesdataintheclientcacheandconnectstheregiontotheservers.

CACHING_PROXY_ENTRY_LRU

storesdataintheclientcacheandconnectstheregiontotheservers.Limitstheamountofdatastoredlocallyintheclienttoadefaultlimitof100,000entriesbyejectingtheleastrecentlyused(LRU)entries.

LOCAL

storesdataintheclientcacheanddoesnotconnecttheregiontotheservers.Thisisaclient-side-onlyregion.

LOCAL_ENTRY_LRU

©CopyrightPivotalSoftwareInc,2013-2019 43 10.0

Page 44: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

storesdataintheclientcacheanddoesnotconnecttheregiontotheservers.Thisisaclient-side-onlyregion.Limitstheamountofdatastoredlocallyintheclienttoadefaultlimitof100,000entriesbyejectingtheleastrecentlyused(LRU)entries.

©CopyrightPivotalSoftwareInc,2013-2019 44 10.0

Page 45: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

SerializingDataDatainyourclientapplication’sGemFirecachemustbeserializabletobesharedwithGemFireserversandotherGemFireclients.GemFireprovidesmultipledataserializationoptionsforstorageandtransmittalbetweenprocesses,ofwhichGemFirePortableDataeXchange(PDX)serializationoffersthebestcombinationofversatilityandease-of-useformostapplications.

Tolearnmoreaboutotherserializationoptions,seetheDataSerializationsectioninthePivotalGemFireUserGuide .

ImplementingaPdxSerializableCustomClassPdxSerializableprovidescustomserializationtoanindividualclass.Fieldswithinanobjectcanbeserializedseparatelyfromtherestoftheclass.

Thetypeofserializationanditsimplementationcanbespecifiedentirelyintheclientapplication,withnoneedtocreatecorrespondingcodeontheGemFireserver.

Setup

PdxSerializableprovidescustomserializationtoanindividualclass.Fieldswithinanobjectcanbeserializedseparatelyfromtherestoftheclass.

SettingupacustomclassforPdxSerializabletreatmentrequiressomepreparatorysteps:

Thecustomclassmustinheritfromthe.NETIPdxSerializableinterfaceortheC++PdxSerializableinterface.

Youmustprovideserializationinstructionsforobjectsofthecustomclass.Specifically:

Youmustimplementthe ToData() and FromData() methodsfor.NETapplications,orthetoData() and fromData() methodsinC++applications.Youmustprovidea“factorymethod”thatreturnsaninstanceofthecustomobject.

Yourapplicationmustregisteryourcustomclasswiththecache,whichtakescareofinformingtheserverofyourserializationscheme.Withregistration,youprovidethenameofthe“factorymethod”youcreatedforinstantiatingobjectsofthecustomclass.

©CopyrightPivotalSoftwareInc,2013-2019 45 10.0

Page 46: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

PdxSerializableExamplesThenativeclientreleasecontainsexamples,writtenfor.NETandC++,showinghowaclientapplicationcanregisterforserializationofcustomobjectsusingthe.NETIPdxSerializableinterfaceortheC++PdxSerializableinterface.

Theexamplesarelocatedin examples\dotnet\pdxserializable and examples/cpp/pdxserializable ,respectively.

Theexamplesdefinetheserializableclass, Orders ,includingitsserializationanddeserializationmethodsanditsfactorymethod.Oncethesepiecesareinplace,executionissimple:themainroutineoftheexampleregisterstheserializableclassthenperformssomeputandgetoperations.

Execution

Bothexamplesperformthesamesequenceofoperations,displayingsimplelogentriesastheyrun.

Torunanexample,followtheinstructionsintheREADME.mdfileintheexampledirectory.

Reviewthesourcecodeintheexampledirectorytoseeexactlyhowitoperates.

Beginbyrunningascriptthatsetsuptheserver-sideenvironmentbyinvoking gfsh commandstocreatearegion,alocator,andaserver.

Runtheexampleclientapplication,whichperformsthefollowingsteps:

ConnectstotheserverRegistersthePdxSerializableclassCreatesordersStoresordersRetrievesorders

.NETExample

Thissectioncontainscodesnippetsshowinghighlightsofthe.NETPdxSerializableexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.

©CopyrightPivotalSoftwareInc,2013-2019 46 10.0

Page 47: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

The.NETexampledefinesaPdxSerializableclasscalled Order thatinheritsfromthe IPdxSerializableinterface.An Order objectcontainsthreefields:

aninteger order_id

astring name

ashort-int quantity

FromOrder.cs:

publicclassOrder:IPdxSerializable{...publiclongOrderId{get;set;}publicstringName{get;set;}publicshortQuantity{get;set;}

Usingthe IPdxSerializable readandwritemethods,the Order classdefines ToData() and FromData()

methodsthatperformtheserializationanddeserializationoperations,respectively,andtheCreateDeserializable() factorymethod:

FromOrder.cs:

publicvoidToData(IPdxWriteroutput){output.WriteLong(ORDER_ID_KEY_,OrderId);output.MarkIdentityField(ORDER_ID_KEY_);

output.WriteString(NAME_KEY_,Name);output.MarkIdentityField(NAME_KEY_);

output.WriteInt(QUANTITY_KEY_,Quantity);output.MarkIdentityField(QUANTITY_KEY_);}

publicvoidFromData(IPdxReaderinput){OrderId=input.ReadLong(ORDER_ID_KEY_);Name=input.ReadString(NAME_KEY_);Quantity=(short)input.ReadInt(QUANTITY_KEY_);}

publicstaticIPdxSerializableCreateDeserializable(){returnnewOrder();}

©CopyrightPivotalSoftwareInc,2013-2019 47 10.0

Page 48: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

The.NETexamplemainlinecreatesacache,thenusesittoregisterthePdxSerializableclassthatwascreatedinOrders.cs:

varcacheFactory=newCacheFactory().Set("log-level","none");varcache=cacheFactory.Create();

cache.TypeRegistry.RegisterPdxType(Order.CreateDeserializable);

Theclientcreatesaconnectionpoolandaregionnamed“example_orderobject”:

varpoolFactory=cache.GetPoolFactory().AddLocator("localhost",10334);poolFactory.Create("pool");

varregionFactory=cache.CreateRegionFactory(RegionShortcut.PROXY).SetPoolName("pool");varorderRegion=regionFactory.Create<int,Order>("example_orderobject");

Afterdeclaringsomekeysandvalues,theclientthenstoresandretrievesan Order object:

constintorderKey=65;

varorder=newOrder(orderKey,"Donuts",12);

Console.WriteLine("ordertoputis"+order);orderRegion.Put(orderKey,order,null);

Console.WriteLine("Successfullyputorder,gettingnow...");varorderRetrieved=orderRegion.Get(orderKey,null);

Console.WriteLine("Orderkey:"+orderKey+"="+orderRetrieved);

Finally,theapplicationclosesthecache:

cache.Close();

C++Example

ThissectioncontainscodesnippetsshowinghighlightsoftheC++PdxSerialiableexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.

©CopyrightPivotalSoftwareInc,2013-2019 48 10.0

Page 49: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

TheC++exampledefinesaPdxSerializableclasscalled Order thatinheritsfromthe PdxSerializableinterface.An Order objectcontainsthreefields:

aninteger order_id

astring name

ashort-int quantity

FromOrder.hpp:

classOrder:publicPdxSerializable{public:...

private:int32_torder_id_;std::stringname_;int16_tquantity_;};

UsingthePdxSerializablereadandwritemethods,the Order classdefines fromData() and toData()

methodsthatperformthedeserializationandserializationoperations,respectively,andthecreateDeserializable() factorymethod:

FromOrder.cpp:

©CopyrightPivotalSoftwareInc,2013-2019 49 10.0

Page 50: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

voidOrder::fromData(PdxReader&pdxReader){order_id_=pdxReader.readInt(ORDER_ID_KEY_);name_=pdxReader.readString(NAME_KEY_);quantity_=pdxReader.readShort(QUANTITY_KEY_);}

voidOrder::toData(PdxWriter&pdxWriter)const{pdxWriter.writeInt(ORDER_ID_KEY_,order_id_);pdxWriter.markIdentityField(ORDER_ID_KEY_);

pdxWriter.writeString(NAME_KEY_,name_);pdxWriter.markIdentityField(NAME_KEY_);

pdxWriter.writeShort(QUANTITY_KEY_,quantity_);pdxWriter.markIdentityField(QUANTITY_KEY_);}

...

std::shared_ptr<PdxSerializable>Order::createDeserializable(){returnstd::make_shared<Order>();}

TheC++examplemainlinecreatesacache,thenusesittocreateaconnectionpoolandaregionobject(ofclass Region ).

autocacheFactory=CacheFactory();cacheFactory.set("log-level","none");autocache=cacheFactory.create();autopoolFactory=cache.getPoolManager().createFactory();

poolFactory.addLocator("localhost",10334);autopool=poolFactory.create("pool");autoregionFactory=cache.createRegionFactory(RegionShortcut::PROXY);autoregion=regionFactory.setPoolName("pool").create("custom_orders");

TheclientregistersthePdxSerializableclassthatwascreatedinOrders.cpp:

cache.getTypeRegistry().registerPdxType(Order::createDeserializable);

Theclienttheninstantiatesandstorestwo Order objects:

©CopyrightPivotalSoftwareInc,2013-2019 50 10.0

Page 51: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

autoorder1=std::make_shared<Order>(1,"productx",23);autoorder2=std::make_shared<Order>(2,"producty",37);

region->put("Customer1",order1);region->put("Customer2",order2);

Next,theapplicationretrievesthestoredvalues,inonecaseextractingthefieldsdefinedintheserializationcode:

if(autoorder1retrieved=std::dynamic_pointer_cast<Order>(region->get("Customer1"))){std::cout<<"OrderID:"<<order1retrieved->getOrderId()<<std::endl;std::cout<<"ProductName:"<<order1retrieved->getName()<<std::endl;std::cout<<"Quantity:"<<order1retrieved->getQuantity()<<std::endl;}else{std::cout<<"Order1notfound."<<std::endl;}

Theapplicationretrievesthesecondobjectanddisplaysitwithoutextractingtheseparatefields:

if(region->existsValue("rtimmons")){std::cout<<"rtimmons'sinfonotdeleted"<<std::endl;}else{std::cout<<"rtimmons'sinfosuccessfullydeleted"<<std::endl;}

Finally,theapplicationclosesthecache:

cache.close();

©CopyrightPivotalSoftwareInc,2013-2019 51 10.0

Page 52: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

RemoteQueriesInthistopic

RemoteQueryBasicsQuerylanguage:OQL

CreatingIndexes

RemoteQueryAPIQuery

ExecutingaQueryfromtheClient

.NETQueryExample

C++QueryExample

UsetheremotequeryAPItoqueryyourcacheddatastoredonacacheserver.

RemoteQueryBasicsQueriesareevaluatedandexecutedonthecacheserver,andtheresultsarereturnedtotheclient.Youcanoptimizeyourqueriesbydefiningindexesonthecacheserver.

Queryingandindexingoperateonlyonremotecacheservercontents.

Querylanguage:OQL

GemFireprovidesaSQL-likequeryinglanguagecalledOQLthatallowsyoutoaccessdatastoredinGemFireregions.OQLisverysimilartoSQL,butOQLallowsyoutoquerycomplexobjects,objectattributes,andmethods.

Inthecontextofaquery,specifythenameofaregionbyitsfullpath,startingwithaslash( / ).

Thequerylanguagesupportsdrillingdownintonestedobjectstructures.NesteddatacollectionscanbeexplicitlyreferencedintheFROMclauseofaquery.

Aqueryexecutionreturnsitsresultsaseithera ResultSet ora StructSet .

QuerylanguagefeaturesandgrammararedescribedintheGemFiremanualatQuerying .

©CopyrightPivotalSoftwareInc,2013-2019 52 10.0

Page 53: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

CreatingIndexes

Indexescanprovidesignificantperformancegainsforqueryexecution.Youcreateandmaintainindexesonthecacheserver.Fordetailedinformationaboutworkingwithindexesconfiguredonacacheserver,seeWorkingwithIndexes intheserver’sdocumentation.

RemoteQueryAPIThissectiongivesageneraloverviewoftheinterfacesandclassesthatareprovidedbythequerypackageAPI.

Query

Youmustcreatea Query objectforeachnewquery.The Query interfaceprovidesmethodsformanagingthecompilationandexecutionofqueries,andforretrievinganexistingquerystring.

A Query isobtainedfroma QueryService ,whichisobtainedfromoneoftwosources:

Tocreatea Query thatoperatesontheGemFireserver,startwitha QueryService obtainedfromaPool .

For.NET,use Apache::Geode::Client::Pool::GetQueryService() .ForC++,use apache::geode::client::Pool::getQueryService() .

Tocreatea Query thatoperatesonyourapplication’slocalcache,startwitha QueryService obtainedfroma Cache .

For.NET,use Apache::Geode::Client::Cache::GetQueryService() .ForC++,use apache::geode::client::Cache::getQueryService() .

ExecutingaQueryfromtheClient

Theessentialstepstocreateandexecuteaqueryare:

1. Createaninstanceofthe QueryService class.IfyouareusingthepoolAPI(recommended),youshouldobtainthe QueryService fromthepool.

2. Createa Query instancethatiscompatiblewiththeOQLspecification.

3. Usethe Query.execute() methodtosubmitthequerystringtothecacheserver.Theserverremotelyevaluatesthequerystringandreturnstheresultstotheclient.

©CopyrightPivotalSoftwareInc,2013-2019 53 10.0

Page 54: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

4. Iteratethroughthereturnedobjects.

.NETQueryExample

TheseC#codeexcerptsarefromthe examples\dotnet\remotequery exampleincludedinyourclientdistribution.Seetheexampleforfullcontext.

Followingthestepslistedabove,

1. Obtaina QueryService objectfromtheconnectionpool:

varqueryService=pool.GetQueryService();

2. Createa Query objectbycalling QueryService.NewQuery() ,specifyingyourOQLqueryasastringparameter:

varquery=queryService.NewQuery<Order>("SELECT*FROM/custom_ordersWHEREquantity>30");

3. Executethequery.Collectthequeryoutput,returnedaseithera ResultSet ora StructSet ,anditeratethroughtheresults:

varqueryResults=query.Execute();

foreach(OrdervalueinqueryResults){Console.WriteLine(value.ToString());}

C++QueryExample

TheseC++codeexcerptsarefromthe examples/cpp/remotequery exampleincludedinyourclientdistribution.Seetheexampleforfullcontext.

Followingthestepslistedabove,

1. Obtaina QueryService objectfromtheconnectionpool:

std::shared_ptr<QueryService>queryService=nullptr;queryService=pool->getQueryService();

©CopyrightPivotalSoftwareInc,2013-2019 54 10.0

Page 55: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

2. Createa Query objectbycalling QueryService.newQuery() ,specifyingyourOQLqueryasastringparameter:

autoquery=queryService->newQuery("SELECT*FROM/custom_ordersWHEREquantity>30");

3. Executethequery.Collectthequeryoutput,returnedaseithera ResultSet ora StructSet ,anditeratethroughtheresults:

autoqueryResults=query->execute();

for(auto&&value:*queryResults){auto&&order=std::dynamic_pointer_cast<Order>(value);std::cout<<order->toString()<<std::endl;}

©CopyrightPivotalSoftwareInc,2013-2019 55 10.0

Page 56: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

ContinuousQueriesInthistopic

ContinuousQueryBasics

TypicalContinuousQueryLifecycle

ExecutingaContinuousQueryfromtheClient.NETContinuousQueryExample

C++ContinuousQueryExample

TheC++and.NETclientscaninitiatequeriesthatrunontheGemFirecacheserverandnotifytheclientwhenthequeryresultshavechanged.Fordetailsontheserver-sidesetupforcontinuousqueries,seeHowContinuousQueryingWorks intheGemFireUserGuide.

ContinuousQueryBasicsContinuousqueryingprovidesthefollowingfeatures:

StandardGemFirenativeclientquerysyntaxandsemantics.Continuousqueriesareexpressedinthesamelanguageusedforothernativeclientqueries.SeeRemoteQueries.

StandardGemFireevents-basedmanagementofCQevents.TheeventhandlingusedtoprocessCQeventsisbasedonthestandardGemFireeventhandlingframework.

Completeintegrationwiththeclient/serverarchitecture.CQfunctionalityusesexistingserver-to-clientmessagingmechanismstosendevents.Alltuningofyourserver-to-clientmessagingalsotunesthemessagingofyourCQevents.IfyoursystemisconfiguredforhighavailabilitythenyourCQsarehighlyavailable,withseamlessfailoverprovidedincaseofserverfailure(seeHighAvailabilityforClient-to-ServerCommunication ).Ifyourclientsaredurable,youcanalsodefineanyofyourCQsasdurable(seeDurableClientMessaging ).

Interestcriteriabasedondatavalues.Continuousqueriesarerunagainsttheregion’sentryvalues.ComparethistoregisterinterestbyreviewingRegisteringInterestforEntries.

Activequeryexecution.Onceinitialized,thequeriesoperateonnewevents.Eventsthatchangethequeryresultaresenttotheclientimmediately.

TypicalContinuousQueryLifecycle1. TheclientcreatestheCQ.Thissetsupeverythingforrunningthequeryandprovidestheclientwitha

CqQuery object,butdoesnotexecutetheCQ.Atthispoint,thequeryisina STOPPED state,readytobeclosedorrun.

©CopyrightPivotalSoftwareInc,2013-2019 56 10.0

Page 57: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

2. TheclientinitiatestheCQwithanAPIcalltooneofthe CqQueryexecute* methods.Thisputsthequeryintoa RUNNING stateontheclientandontheserver.Theserverremotelyevaluatesthequerystring,andoptionallyreturnstheresultstotheclient. CqQueryexecute* methodsinclude:

.NET: CqQuery.Execute() and CqQuery.ExecuteWithInitialResults()C++: CqQuery.execute() and CqQuery.executeWithInitialResults()

3. ACQListenerwaitsforevents.Whenitreceivesevents,ittakesactionaccordinglywiththedataintheCqEvent.

4. TheCQisclosedbyaclientcallto CqQuery.close .Thisde-allocatesallresourcesinusefortheCQontheclientandserver.Atthispoint,thecyclecouldbeginagainwiththecreationofanew CqQuery instance.

ExecutingaContinuousQueryfromtheClientTheessentialstepstocreateandexecuteacontinuousqueryare:

1. Createaninstanceofthe QueryService class.IfyouareusingthepoolAPI(recommended),youshouldobtainthe QueryService fromthepool.

2. DefineaCQListener(in.NET,an ICqListener ,inC++,a CqListener )tofieldeventssentfromtheserver.

3. Useoneofthe CqQuery execute* methodstosubmitthequerystringtothecacheserver.

4. Theserverremotelyevaluatesthequerystring,thenmonitorsthoseresultsandnotifiestheclientiftheychange.

5. Theclientlistensforchangesthatmatchthequerypredicate.

6. Iteratethroughthereturnedobjects.

7. Whenfinished,closedownthecontinuousquery.

.NETContinuousQueryExample

TheseC#codeexcerptsarefromthe examples\dotnet\continuousquery exampleincludedinyourclientdistribution.Seetheexampleforfullcontext.

Followingthestepslistedabove,

1. Createaqueryservice:

©CopyrightPivotalSoftwareInc,2013-2019 57 10.0

Page 58: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

varqueryService=pool.GetQueryService();

2. DefineanICqListener:

publicclassMyCqListener<TKey,TResult>:ICqListener<TKey,TResult>{

3. CreateaninstanceofyourICqListenerandinsertitintoaCQattributesobject:

varcqListener=newMyCqListener<string,Order>();varcqAttributesFactory=newCqAttributesFactory<string,Order>();cqAttributesFactory.AddCqListener(cqListener);varcqAttributes=cqAttributesFactory.Create();

4. CreateaContinuousQueryusingthequeryserviceandtheCQattributes:

varquery=queryService.NewCq("MyCq","SELECT*FROM/example_orderobjectWHEREquantity>30",cqAttributes,false);

5. Executethequery:

query.Execute();

6. Waitforeventsanddosomethingwiththem.

/*ExcerptfromtheCqListener*/

/*DetermineOperationType*/switch(ev.getQueryOperation()){caseCqOperation.OP_TYPE_CREATE:operationType="CREATE";break;caseCqOperation.OP_TYPE_UPDATE:operationType="UPDATE";break;caseCqOperation.OP_TYPE_DESTROY:operationType="DESTROY";break;default:break;}

...

/*TakeactionbasedonOPType*/

©CopyrightPivotalSoftwareInc,2013-2019 58 10.0

Page 59: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

7. Whenfinished,closeupshop.

query.Execute();...(respondtoeventsastheyarrive)

query.Stop();query.Close();

cache.Close();

C++ContinuousQueryExample

TheseC++codeexcerptsarefromthe examples/cpp/continuousquery exampleincludedinyourclientdistribution.Seetheexampleforfullcontext.

Followingthestepslistedabove,

1. Createaqueryservice:

autoqueryService=pool->getQueryService();

2. DefineaCqListener:

classMyCqListener:publicCqListener{

3. CreateaninstanceofyourCqListenerandinsertitintoaCQattributesobject:

CqAttributesFactorycqFactory;

autocqListener=std::make_shared<MyCqListener>();

cqFactory.addCqListener(cqListener);autocqAttributes=cqFactory.create();

4. CreateaContinuousQueryusingthequeryserviceandtheCQattributes:

autoquery=queryService->newCq("MyCq","SELECT*FROM/custom_orderscWHEREc.quantity>30",cqAttributes);

5. Executethequery:

©CopyrightPivotalSoftwareInc,2013-2019 59 10.0

Page 60: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

query->execute();

6. Waitforeventsanddosomethingwiththem.

/*ExcerptfromtheCqListener*/

/*DetermineOperationType*/switch(cqEvent.getQueryOperation()){caseCqOperation::OP_TYPE_CREATE:opStr="CREATE";break;caseCqOperation::OP_TYPE_UPDATE:opStr="UPDATE";break;caseCqOperation::OP_TYPE_DESTROY:opStr="DESTROY";break;default:break;}

...

/*TakeactionbasedonOPType*/

7. Whenfinished,closeupshop.

query->execute();

...(respondtoeventsastheyarrive)

query->stop();query->close();

cache.close();

©CopyrightPivotalSoftwareInc,2013-2019 60 10.0

Page 61: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Security:AuthenticationandEncryptionMostsecurityconfigurationtakesplaceontheGemFireserver.Theserver’ssecurityframeworkauthenticatesclientsastheyconnecttoacacheserverandauthorizesclientcacheoperationsusingdeveloper-providedimplementationsforauthenticationandauthorization.

Foranexplanationoftheserver-sideimplementationofsecurityfeatures,seeSecurity intheGemFireUserGuide.

ANativeClientapplicationmustaddresstwosecurityconcernswhenconnectingtoaGemFireserver:

AuthenticationTheClientmustsubmititsauthenticationcredentialstotheserverusingthedeveloper-providedauthenticationimplementationexpectedbytheserver.

TLS/SSLClient/ServerCommunicationEncryptionCommunicationbetweenclientandservershouldbeencryptedsoauthenticationcredentialsandothertransmissionscannotbeviewedbythird-parties.

©CopyrightPivotalSoftwareInc,2013-2019 61 10.0

Page 62: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

AuthenticationAclientisauthenticatedwhenitconnectswithvalidcredentialstoaGemFirecacheserverthatisconfiguredwiththeclientauthenticationcallback.Fordetailsontheserver’sroleinauthenticationandwhatitexpectsfromtheclient,seeImplementingAuthentication intheGemFireUserGuide.

Inyourapplication,authenticationcredentialsmustbesetwhencreatingthecache.Inpractice,thismeanssettingtheauthenticationcredentialswhenyoucreatetheCacheFactory.

.NETAuthenticationExample

Thefollowingexcerptistakenfromthe.NETexampleprovidedwithyourNativeClientdistributioninthe../examples/dotnet/authinitialize directory.

InthisC#authenticationexample,the CacheFactory creationprocesssetstheauthenticationcallback:

varcacheFactory=newCacheFactory().Set("log-level","none").SetAuthInitialize(newExampleAuthInitialize());

Credentialsareimplementedinthe GetCredentials memberfunctionofthe ExampleAuthInitialize class,whichimplementsthe IAuthInitialize interface:

©CopyrightPivotalSoftwareInc,2013-2019 62 10.0

Page 63: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

classExampleAuthInitialize:IAuthInitialize{publicExampleAuthInitialize(){//TODOinitializeyourresourceshereConsole.Out.WriteLine("ExampleAuthInitialize::ExampleAuthInitializecalled");}

publicvoidClose(){//TODOcloseyourresourceshereConsole.Out.WriteLine("ExampleAuthInitialize::Closecalled");}

publicProperties<string,object>GetCredentials(Properties<string,string>props,stringserver){//TODOgetyourusernameandpasswordConsole.Out.WriteLine("ExampleAuthInitialize::GetCredentialscalled");

varcredentials=newProperties<string,object>();credentials.Insert("security-username","root");credentials.Insert("security-password","root");returncredentials;}}

C++AuthenticationExample

InthisC++authenticationexample,the CacheFactory creationprocesssetstheauthenticationcallback:

autocacheFactory=CacheFactory(config);autoauthInitialize=std::make_shared<UserPasswordAuthInit>();cacheFactory.set("log-level","none");cacheFactory.setAuthInitialize(authInitialize);

Credentialsareimplementedinthe getCredentials memberfunctionofthe AuthInitialize abstractclass.

©CopyrightPivotalSoftwareInc,2013-2019 63 10.0

Page 64: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

classUserPasswordAuthInit:publicAuthInitialize{public:UserPasswordAuthInit()=default;

~UserPasswordAuthInit()noexceptoverride=default;

std::shared_ptr<Properties>getCredentials(conststd::shared_ptr<Properties>&securityprops,conststd::string&)override{std::shared_ptr<Cacheable>userName;if(securityprops==nullptr||(userName=securityprops->find(SECURITY_USERNAME))==nullptr){throwAuthenticationFailedException("UserPasswordAuthInit:username""property[SECURITY_USERNAME]notset.");}

autocredentials=Properties::create();credentials->insert(SECURITY_USERNAME,userName->toString().c_str());autopasswd=securityprops->find(SECURITY_PASSWORD);if(passwd==nullptr){passwd=CacheableString::create("");}credentials->insert(SECURITY_PASSWORD,passwd->value().c_str());returncredentials;}

voidclose()override{return;}};

©CopyrightPivotalSoftwareInc,2013-2019 64 10.0

Page 65: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

TLS/SSLClient-ServerCommunicationEncryptionThissectiondescribeshowtoimplementTLS-basedcommunicationbetweenyourclientsandserversusingtheOpenSSLencryptionutility.WhenconfiguringTLS/SSLsecurityforyourclient,youmayfindithelpfultorefertoTheSSLsectionoftheGemFireUserGuide .

SetUpOpenSSL

Theopen-sourceOpenSSLtoolkitprovidesafull-strengthgeneralpurposecryptographylibraryforencryptingclient-servercommunications.

DownloadandinstallOpenSSL1.1.1foryourspecificoperatingsystem.

NotesforWindowsusers:

ForWindowsplatforms,youcanuseeithertheregularorthe“Light”versionofSSL.

Usea64-bitimplementationofOpenSSL.

IfyouuseCygwin,donotusetheOpenSSLlibrarythatcomeswithCygwin,whichisbuiltwithcygwin.dll asadependency.Instead,downloadafreshcopyfromOpenSSL.

FormanyWindowsapplications,themostconvenientwaytoinstallOpenSSListouse choco (seechocolatey.org )toinstallthe“Light”versionofOpenSSL.

Step1.CreatekeystoresTheGemFireserverrequireskeysandkeystoresintheJavaKeyStore(JKS)formatwhilethenativeclientrequiresthemintheclearPEMformat.Thusyouneedtobeabletogenerateprivate/publickeypairsineitherformatandconvertbetweenthetwousingthe keytool utilityandthe openssl command.

Step2.EnableSSLontheserverandontheclient1. Ontheserver,enableSSLforthe locator and server components,astheSSL-enabledclientmust

beabletocommunicatewithbothlocatorandservercomponents.

2. Ontheclient,set ssl-enabled to true .

3. Ontheclient,set ssl-keystore and ssl-truststore topointtoyourkeystorefiles.Pathstothekeystoreandtruststorearelocaltotheclient.SeeSecurity-RelatedSystemProperties foradescriptionoftheseproperties.

©CopyrightPivotalSoftwareInc,2013-2019 65 10.0

Page 66: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

StartingandstoppingtheclientandserverwithSSLinplace

Beforeyoustartandstoptheclientandserver,makesureyouconfigurethenativeclientwiththeSSLpropertiesasdescribedandwiththeserversorlocatorsspecifiedasusual.

Specifically,ensurethat:

TheOpenSSLandGemFireDLLsareintherightenvironmentvariablesforyoursystem: PATH forWindows,and LD_LIBRARY_PATH forUnix.

Youhavegeneratedthekeysandkeystores.

Youhavesetthesystemproperties.

FordetailsonstoppingandstartinglocatorsandcacheserverswithSSL,seeStartingUpandShuttingDownYourSystem .

TheGemFireNative’slibcryptoImplfoundin/libmustbelinkedatcompiletime.ThisbinaryisusedtointeractwithOpenSSL.LinklibcryptoImpl,nativeclient,andyourapplicationcode.Wehighlyrecommendusingcmake.

Examplelocatorstartcommand

EnsurethatallrequiredSSLpropertiesareconfiguredinyourserver’s geode.properties file.Thenstartyourlocatorasfollows:

gfsh>startlocator--name=my_locator--port=12345--dir=.\--security-properties-file=/path/to/your/geode.properties

Examplelocatorstopcommand

gfsh>stoplocator--port=12345\--security-properties-file=/path/to/your/geode.properties

Exampleserverstartcommand

Again,ensurethatallrequiredSSLpropertiesareconfiguredin geode.properties .Thenstarttheserverwith:

gfsh>startserver--name=my_server--locators=hostname[12345]\--cache-xml-file=server.xml--log-level=fine\--security-properties-file=/path/to/your/geode.properties

©CopyrightPivotalSoftwareInc,2013-2019 66 10.0

Page 67: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Exampleserverstopcommand

gfsh>stopserver--name=my_server

©CopyrightPivotalSoftwareInc,2013-2019 67 10.0

Page 68: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

FunctionExecutionInthistopic

Server-sideRequirements

Client-sideRequirements

HowFunctionsExecute

ProcessingFunctionResults

FunctionExecutionExamples.NETExample

C++Example

Aclientcaninvokeaserver-residentfunction,withparameters,andcancollectandoperateonthereturnedresults.

Server-sideRequirementsTobecallablefromyourclient,afunctionmustbe

residentontheserver,and

registeredasavailableforclientaccess.

SeeExecutingaFunctioninPivotalGemFire intheGemFireUserGuidefordetailsonhowtowriteandregisterserver-residentfunctions.

Client-sideRequirementsTheclientmustconnecttotheserverthroughaconnectionpoolinordertoinvokeaserver-sidefunction.

HowFunctionsExecute1. Thecallingclientapplicationrunsthe execute methodonthe Execution object.Thefunction

mustalreadyberegisteredontheservers.

2. Thefunctionisinvokedontheserverswhereitneedstorun.TheserversaredeterminedbytheFunctionService on* methodcalls,regionconfiguration,andanyfilters.

©CopyrightPivotalSoftwareInc,2013-2019 68 10.0

Page 69: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

3. Ifthefunctionhasresults,theresultisreturnedina ResultCollector object.

4. Theclientcollectsresultsusingthe ResultCollector.getResult() method.

Ineveryclientwhereyouwanttoexecutethefunctionandprocesstheresults:

Useoneofthe FunctionService on* methodstocreatean Execution object.The on* methods,onRegion , onServer and onServers ,definethehighestlevelwherethefunctionisrun.

Ifyouuse onRegion youcanfurthernarrowyourrunscopebysettingkeyfilters.

Afunctionrunusing onRegion isadatadependentfunction–othersaredata-independentfunctions.

Youcanrunadatadependentfunctionagainstpartitionedandcolocatedpartitionedregions.Fromtheclient,providetheappropriatekeysetstothefunctioncall.

The Execution objectallowsyoutocustomizetheinvocationby:

Providingasetofdatakeysto withFilter tonarrowtheexecutionscope.ThisworksonlyforonRegion Executionobjects(data-dependentfunctions).Providingfunctionargumentsto withArgs .Definingacustom ResultCollector for withCollector .

Callthe Execution.execute() methodtorunthefunction.

ProcessingFunctionResultsTogettheresultsfromthefunctionintheclientapp,usetheresultcollectorreturnedfromthefunctionexecution.The getResult methodsofthedefaultresultcollectorblockuntilallresultsarereceived,thenreturnthefullresultset.

Theclientcanusethedefaultresultcollector.Iftheclientneedsspecialresultshandling,codeacustomResultsCollector implementationtoreplacethedefault.Usethe Execution::withCollector methodtospecifythecustomcollector.Tohandletheresultsinacustommanner:

1. Writeaclassthatimplementsthe ResultCollector interfacetohandletheresultsinacustommanner.Themethodsareoftwotypes:onehandlesdataandinformationfromGemFireandpopulatestheresultsset,whiletheotherreturnsthecompiledresultstothecallingapplication:

addResult iscalledwhenresultsarrivefromthe Function methods.Use addResult toaddasingleresulttotheResultCollector.endResults iscalledtosignaltheendofallresultsfromthefunctionexecution.getResult isavailabletoyourexecutingapplication(theonethatcallsExecution.execute )toretrievetheresults.Thismayblockuntilallresultsareavailable.

©CopyrightPivotalSoftwareInc,2013-2019 69 10.0

Page 70: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

clearResults iscalledtoclearpartialresultsfromtheresultscollector.Thisisusedonlyforhighlyavailable onRegion functionswherethecallingapplicationwaitsfortheresults.Ifthecallfails,beforeGemFireretriestheexecution,itcalls clearResults toreadytheinstanceforacleansetofresults.

2. Usethe Execution objectinyourexecutingmembertocall withCollector ,passingyourcustomcollector.

FunctionExecutionExamplesThenativeclientreleasecontainsexamplesoffunctionexecutionwrittenfor.NETandC++.Theexamplesarelocatedin ../examples/dotnet/functionexecution and ../examples/cpp/functionexecution ,respectively.

Thetwoexamplessharesomecommonelements:

Theybeginwithaserver-sidescriptthatruns gfsh commandstocreatearegion,simplycalled“partition_region”.

ThefunctionispreloadedwithaJARfilecontainingtheserver-sideJavafunctioncode.

Thefunction,called“ExampleMultiGetFunction”,isdefinedinthe examples/utilities directoryofyourdistribution.Asitsinputparameter,thefunctiontakesanarrayofkeys,thenperformsa get oneachkeyandreturnsanarraycontainingtheresults.

Thefunctiondoesnotloadvaluesintothedatastore.Thatisaseparateoperation,performedintheseexamplesbytheclient,anddoesnotinvolvetheserver-sidefunction.

Asprerequisites,theclientcodemustbeawareoftheconnectiontotheserver,thenameofthefunction,andtheexpectedtype/formatoftheinputparameterandreturnvalue.

Theclient:

createsanexecutionobject

providestheexecutionobjectwithapopulatedinputparameterarray

invokestheobject’sexecutemethodtoinvoketheserver-sidefunction

Iftheclientexpectsresults,itmustcreatearesultobject.The.NETexampleusesabuilt-inresultcollector( IResultCollector.getResults() )toretrievethefunctionresults.

TheC++examplecreatesaresultvariabletoholdtheresultsfromthecollector.

.NETExample

©CopyrightPivotalSoftwareInc,2013-2019 70 10.0

Page 71: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Thissectioncontainscodesnippetsshowinghighlightsofthe.NETfunctionexecutionexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.

The.NETexamplecreatesacache,thenusesittocreateaconnectionpool.

varcacheFactory=newCacheFactory().Set("log-level","none");varcache=cacheFactory.Create();

varpoolFactory=cache.GetPoolFactory().AddLocator("localhost",10334);varpool=poolFactory.Create("pool");

Theexampleusestheconnectionpooltocreatearegion,withthesamecharacteristicsandnameastheserver-sideregion( partition_region ).

varregionFactory=cache.CreateRegionFactory(RegionShortcut.PROXY).SetPoolName("pool");varregion=regionFactory.Create<object,object>("partition_region");

Thesampleclientpopulatestheserver’sdatastorewithvalues,usingtheAPIandsomesamplekey-valuepairs.

stringrtimmonsKey="rtimmons";stringrtimmonsValue="RobertTimmons";stringscharlesKey="scharles";stringscharlesValue="SylviaCharles";region.Put(rtimmonsKey,rtimmonsValue,null);region.Put(scharlesKey,scharlesValue,null);

Toconfirmthatthedatahasbeenstored,theclientusestheAPItoretrievethevaluesandwritethemtotheconsole.Thisisdonewithoutreferencetotheserver-sideexamplefunction.

varuser1=region.Get(rtimmonsKey,null);varuser2=region.Get(scharlesKey,null);

Console.WriteLine(rtimmonsKey+"="+user1);Console.WriteLine(scharlesKey+"="+user2);

Next,theclientretrievesthosesamevaluesusingtheserver-sideexamplefunction.Theclientcodecreatestheinputparameter,anarrayofkeyswhosevaluesaretoberetrieved.

©CopyrightPivotalSoftwareInc,2013-2019 71 10.0

Page 72: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

ArrayListkeyArgs=newArrayList();keyArgs.Add(rtimmonsKey);keyArgs.Add(scharlesKey);

Theclientcreatesanexecutionobjectusing Client.FunctionService.OnRegion andspecifyingtheregion.

varexc=Client.FunctionService<object>.OnRegion<object,object>(region);

TheclientthencallstheserversidefunctionwithitsinputargumentsandstorestheresultsinaClient.IResultCollector.

Client.IResultCollector<object>rc=exc.WithArgs<object>(keyArgs).Execute("ExampleMultiGetFunction");

Itthenloopsthroughtheresultsandprintstheretrievedvalues.

ICollection<object>res=rc.GetResult();

Console.WriteLine("FunctionExecutionResults:");Console.WriteLine("Count={0}",res.Count);

foreach(List<object>iteminres){foreach(objectitem2initem){Console.WriteLine("value={0}",item2.ToString());}}

C++Example

ThissectioncontainscodesnippetsshowinghighlightsoftheC++functionexecutionexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.

TheC++examplecreatesacache.

CachesetupCache(){returnCacheFactory().set("log-level","none").create();}

©CopyrightPivotalSoftwareInc,2013-2019 72 10.0

Page 73: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Theexampleclientusesthecachetocreateaconnectionpool,

voidcreatePool(constCache&cache){autopool=cache.getPoolManager().createFactory().addServer("localhost",EXAMPLE_SERVER_PORT).create("pool");}

Then,usingthatpool,theclientcreatesaregionwiththesamecharacteristicsandnameastheserver-sideregion( partition_region ).

std::shared_ptr<Region>createRegion(Cache&cache){autoregionFactory=cache.createRegionFactory(RegionShortcut::PROXY);autoregion=regionFactory.setPoolName("pool").create("partition_region");

returnregion;}

Thesampleclientpopulatestheserver’sdatastorewithvalues,usingtheAPIandsomesamplekey-valuepairs.

voidpopulateRegion(conststd::shared_ptr<Region>&region){for(inti=0;i<keys.size();i++){region->put(keys[i],values[i]);}}

Asconfirmationthatthedatahasbeenstored,thesampleclientusestheAPItoretrievethevaluesandwritethemtotheconsole.Thisisdonewithoutreferencetotheserver-sideexamplefunction.

std::shared_ptr<CacheableVector>populateArguments(){autoarguments=CacheableVector::create();for(inti=0;i<keys.size();i++){arguments->push_back(CacheableKey::create(keys[i]));}returnarguments;}

Next,theclientretrievesthosesamevaluesusingtheserver-sideexamplefunction.Theclientcodecreatestheinputparameter,anarrayofkeyswhosevaluesaretoberetrieved.

©CopyrightPivotalSoftwareInc,2013-2019 73 10.0

Page 74: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

std::vector<std::string>executeFunctionOnServer(conststd::shared_ptr<Region>region,conststd::shared_ptr<CacheableVector>arguments){std::vector<std::string>resultList;

Theclientcreatesanexecutionobjectusing Client.FunctionService.OnRegion andspecifyingtheregion.

autofunctionService=FunctionService::onServer(region->getRegionService());

Theclientthencallstheserversidefunctionwithitsinputargumentsandstorestheresultsinavector.

if(autoexecuteFunctionResult=functionService.withArgs(arguments).execute(getFuncIName)->getResult()){for(auto&arrayList:*executeFunctionResult){for(auto&cachedString:*std::dynamic_pointer_cast<CacheableArrayList>(arrayList)){resultList.push_back(std::dynamic_pointer_cast<CacheableString>(cachedString)->value());}}}else{std::cout<<"getexecuteFunctionResultisNULL\n";}

returnresultList;}

Itthenloopsthroughtheresultsvectorandprintstheretrievedvalues.

voidprintResults(conststd::vector<std::string>&resultList){std::cout<<"Resultcount="<<resultList.size()<<std::endl<<std::endl;inti=0;for(auto&cachedString:resultList){std::cout<<"\tResult["<<i<<"]="<<cachedString<<std::endl;++i;}

©CopyrightPivotalSoftwareInc,2013-2019 74 10.0

Page 75: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

TransactionsInthistopic

NativeClientTransactionAPIs

RunningNativeClientTransactions

ClientTransactionExamples.NETExample

C++Example

TheNativeClientAPIrunstransactionsontheserverasiftheywerelocaltotheclientapplication.Thus,thekeytorunningclienttransactionsliesinmakingsuretheserverisproperlyconfiguredandprogrammed.ForcompleteinformationabouthowtransactionsareconductedontheGemFireserver,seetheTransactionssectionoftheGemFireUserGuide.

NativeClientTransactionAPIsTheAPIfordistributedtransactionshasthefamiliarrelationaldatabasemethods, begin , commit ,androllback .TherearealsoAPIsavailabletosuspendandresumetransactions.

The.NETclassesforexecutingtransactionsare:

Apache.Geode.Client.CacheTransactionManager

Apache.Geode.Client.TransactionId

TheC++classesforexecutingtransactionsare:

apache.geode.client.CacheTransactionManager

apache.geode.client.TransactionId

RunningNativeClientTransactionsThesyntaxforwritingclienttransactionsisthesameaswithserverorpeertransactions,butwhenaclientperformsatransaction,thetransactionisdelegatedtoaserverthatbrokersthetransaction.

Starteachtransactionwitha begin operation,andendthetransactionwitha commit ora rollback .

©CopyrightPivotalSoftwareInc,2013-2019 75 10.0

Page 76: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Tomaintaincacheconsistency,thelocalclientcacheisnotusedduringatransaction.Whenthetransactioncompletesorissuspended,localcacheusageisreinstated.

Ifthetransactionrunsonserverregionsthatareamixofpartitionedandreplicatedregions,performthefirsttransactionoperationonapartitionedregion.Thissetstheserverdatahostfortheentiretransaction.IfyouareusingPRsingle-hop,single-hopwillbeappliedasusualtothisfirstoperation.

Inadditiontothefailureconditionscommontoalltransactions,clienttransactionscanalsofailifthetransactiondelegatefails.Ifthedelegateperformingthetransactionfails,thetransactioncodethrowsaTransactionException .

ClientTransactionExamplesThenativeclientreleasecontainstransactionexampleswrittenfor.NETandC++.Theexamplesarelocatedin ../examples/dotnet/transaction and ../examples/cpp/transaction ,respectively.

Bothexamplesperformthesamesequenceofoperations,displayingsimplelogentriesastheyrun.

Torunanexample,followtheinstructionsinthe README.md fileintheexampledirectory.

Reviewthesourcecodeintheexampledirectorytoseeexactlyhowitoperates.

Youbeginbyrunningascriptthatsetsuptheserver-sideenvironmentbyinvoking gfsh commandstocreatearegion,simplycalled“exampleRegion.”

Youruntheexampleclientapplication,whichperformsthefollowingsteps:

ConnectstotheserverBeginsatransactionPerformssome put operationsCommitsthetransaction

Forthisexample,thetransactioncodehasthesecharacteristics:

Tointroducethepossibilityoffailure,valuesarerandomizedfrom0to9,andthe0valuesaretreatedasunsuccessful.Thetransactionisretrieduntilitsucceeds.Incasethetransactionrepeatedlyfails,theretryloopusesacountertosetalimitof5retries.

.NETExample

Thissectioncontainscodesnippetsshowinghighlightsofthe.NETtransactionexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.

©CopyrightPivotalSoftwareInc,2013-2019 76 10.0

Page 77: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

The.NETexamplecreatesacache,thenusesittocreateaconnectionpool.

varcache=newCacheFactory().Set("log-level","none").Create();

varpoolFactory=cache.GetPoolFactory().AddLocator("localhost",10334);

poolFactory.Create("pool");

varregionFactory=cache.CreateRegionFactory(RegionShortcut.PROXY).SetPoolName("pool");varregion=regionFactory.Create<string,int>("exampleRegion");

Theexampleapplicationgetsatransactionmanagerfromthecacheandbeginsatransaction.

cache.CacheTransactionManager.Begin();

Withinthetransaction,theclientpopulatesdatastorewith10valuesassociatedwithKey1-Key10.

foreach(varkeyinkeys){varvalue=getValueFromExternalSystem();region.Put(key,value);}

Ifall put operationssucceed,theapplicationcommitsthetransaction.Otherwise,itretriesupto5timesifnecessary.

varretries=5;while(retries-->0){try{...//PUTOPERATIONS...cache.CacheTransactionManager.Commit();Console.WriteLine("Committedtransaction-exiting");break;}catch{cache.CacheTransactionManager.Rollback();Console.WriteLine("Rolledbacktransaction-retrying({0})",retries);}}

©CopyrightPivotalSoftwareInc,2013-2019 77 10.0

Page 78: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

C++Example

ThissectioncontainscodesnippetsshowinghighlightsoftheC++transactionexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.

TheC++examplecreatesacache,thenusesittocreateaconnectionpool.

autocache=CacheFactory().set("log-level","none").create();autopoolFactory=cache.getPoolManager().createFactory();

poolFactory.addLocator("localhost",10334);autopool=poolFactory.create("pool");autoregionFactory=cache.createRegionFactory(RegionShortcut::PROXY);autoregion=regionFactory.setPoolName("pool").create("exampleRegion");

Theexampleapplicationgetsatransactionmanagerfromthecacheandbeginsatransaction.

autotransactionManager=cache.getCacheTransactionManager();

transactionManager->begin();

Withinthetransaction,theclientpopulatesdatastorewith10valuesassociatedwithKey1-Key10.

for(auto&key:keys){autovalue=getValueFromExternalSystem();region->put(key,value);}

Ifall put operationssucceed,theapplicationcommitsthetransaction.Otherwise,itretriesupto5timesifnecessary.

autoretries=5;while(retries--){try{transactionManager->begin();...//PUTOPERATIONS...transactionManager->commit();std::cout<<"Committedtransaction-exiting"<<std::endl;break;}catch(...){transactionManager->rollback();std::cout<<"Rolledbacktransaction-retrying("<<retries<<")"<<std::endl;}}

©CopyrightPivotalSoftwareInc,2013-2019 78 10.0

Page 79: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

©CopyrightPivotalSoftwareInc,2013-2019 79 10.0

Page 80: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

SessionStateProviderThePivotalGemFireSessionlibraryimplementsMicrosoft’sSessionStateStoreProviderBaseAPI .ThesessionstateproviderstoressessionstatedatainaregionontheGemFireserver.

ToincorporatetheGemFiresessionstateproviderintoyourwebapplication:

Provideaconfigurationfileforyourapplication.

Setuptheapplication’sdevelopmentenvironment.

ConfiguretheGemFireserver.

Provideforauthentication,ifyourserverrequiresit.

CreatingorChangingConfigurationFilesCreateormodifyyourclient-sideconfigurationfilestospecifytheregioninwhichsessionstatewillbestored.YourNativeClientdistributionincludes Web.Config ,whichyoucanmodifyasneeded.

Web.ConfigExample

ThenativeclientreleaseforWindowscontainsa Web.Config filesimilartothefollowing.Theconfigurationfile:

Specifiesa sessionState elementthatreferencestheGemFiresessionstateprovider.

Setsthe region variableto sessionStateRegion ,theregiondedicatedforusebythesessionstateprovider.

Inthisexample,theconfigfilespecifiesonelocatorusingtheparameterpair

locator-host="localhost" and locator-port="10334" .Tospecifymultiplelocators,instead,useasingle locators parameterwiththeformlocators="locator1[port1],locator2[port2]" .Thetwoformsaremutuallyexclusive.

Assumingthattheserverrequiressecureconnections,setsfourSSL-relatedparameters:

ssl-enabled

ssl-keystore

ssl-keystore-password

ssl-truststore

©CopyrightPivotalSoftwareInc,2013-2019 80 10.0

Page 81: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<system.web><compilationdebug="true"targetFramework="4.5.2"/><httpRuntimetargetFramework="4.5"/><pages><namespaces><addnamespace="System.Web.Optimization"/></namespaces><controls><addassembly="Microsoft.AspNet.Web.Optimization.WebForms"namespace="Microsoft.AspNet.Web.Optimization.WebForms"tagPrefix="webopt"/></controls></pages><sessionStatemode="Custom"cookieless="false"timeout="1"customProvider="GemFireSessionProvider"><providers><addname="GemFireSessionProvider"type="Pivotal.GemFire.Session.SessionStateStore"region="sessionStateRegion"locator-host="localhost"locator-port="10334"pool-name="default"ssl-enabled="true"ssl-keystore="C:/gemfire-dotnetsession/SampleWebApp/Security/client_keystore.password.pem"ssl-keystore-password="gemstone"ssl-truststore="C:/gemfire-dotnetsession/SampleWebApp/Security/client_truststore.pem"log-file="C:/gemfire-dotnetsession/SampleWebApp/SampleWebApp.log"log-level="fine"/></providers></sessionState></system.web>

ModifyingtheApplication’sDevelopmentEnvironmentInyourdevelopmentenvironment:

Addareferencetotheincluded Pivotal.GemFire.Session librarytoyourapplication’sproject.

Addareferencetotheincluded Pivotal.GemFire librarytoyourapplication’sproject.

Note:Youmustusethematchedpairof Pivotal.GemFire.Session and Pivotal.GemFire librariesfromthesamedistributionoftheGemFireNativeClient.Donotmixtwodifferentversions.

FordeveloperstestinginVisualStudio

UnderTools->Options->ProjectsAndSolutions->WebProjects,enabletheproperty“Use64-bitversionofIISExpress”.

Youmustusea64-bittarget.

ConfiguringtheGemFireServerTousetheGemFiresessionstateprovider,theserver-basedregionnameandtheregionnameyouhavespecifiedinWeb.config mustmatch.Forexample,thefollowing gfsh createregion commandusesthe --name parametertocreatearegionnamed sessionStateRegion .

gfsh>createregion--name="sessionStateRegion"--type=PARTITION`

©CopyrightPivotalSoftwareInc,2013-2019 81 10.0

Page 82: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

TheMicrosoftSessionStateStoreProviderBaseAPI reliesontheappdevelopertoprovideserver-sidefunctionstosaveandrestoresessionstate.ThisdistributionoftheNativeClientprovidesimplementationsoftheexpectedfunctions,packagedasaJARfilein INSTALL_DIR/lib/SessionStateStoreFunctions.jar .

CopytheJARfiletoyourserverthen,aftertheserverisstarted,use gfsh todeploythesessionstatefunctionsontheserver:

gfsh>deploy--jar=YOURPATH/lib/SessionStateStoreFunctions.jar

ConfigureServer-SideLogging

TheGemFireserver-sidesessionfunctionsprovidetracing-levelloggingincaseyouneedsuchdetailsduringappdevelopment.Trace-levelloggingcanbeenabledbysetting log-level=finest or log-level=all intheserverproperties.(Theselog-level settingsgeneratealogofverydetailedlogentries.Remembertorestoreloggingtoahigher,lessverboselevel(suchas log-level=info ,whenthedetailisnolongerneeded.)RefertoLogging intheGemFireUserGuideformoreinformationonserver-sidelogging.

ProvidingAuthentication(optional)Ifexpectedbytheserver,yourclientapplicationmustprovideauthentication.Implementthe IAuthInitialize interfacetospecifycredentials.Forexample:

protectedvoidApplication_Start(objectsender,EventArgse){SessionStateStore.AuthInitialize=newBasicAuthInitialize("john","secret");RouteConfig.RegisterRoutes(RouteTable.Routes);BundleConfig.RegisterBundles(BundleTable.Bundles);}

publicclassBasicAuthInitialize:IAuthInitialize{privatestring_username;privatestring_password;

publicBasicAuthInitialize(stringusername,stringpassword){_username=username;_password=password;}

publicvoidClose(){}

publicProperties<string,object>GetCredentials(Properties<string,string>props,stringserver){varcredentials=newProperties<string,object>();

credentials.Insert("security-username",_username);credentials.Insert("security-password",_password);

returncredentials;}}

©CopyrightPivotalSoftwareInc,2013-2019 82 10.0

Page 83: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

©CopyrightPivotalSoftwareInc,2013-2019 83 10.0

Page 84: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

SystemPropertiesAvarietyofsystempropertiescanbespecifiedwhenaclientconnectstoadistributedsystem,eitherprogrammaticallyorina geode.properties file.

Inthe.NETAPIdocs ,see Apache::Geode::Client::SystemProperties .

IntheC++APIdocs ,see apache::geode::client::SystemProperties .

Thefollowingsettingscanbeconfigured:

GeneralPropertiesBasicinformationfortheprocess,suchascachecreationparameters.

LoggingPropertiesHowandwheretologsystemmessages.

StatisticsArchivingPropertiesHowtocollectandarchivestatisticsinformation.

DurableClientPropertiesInformationaboutthedurableclientsconnectedtothesystem.

SystemPropertiesforClientAuthenticationandAuthorizationInformationaboutvarioussecurityparameters.

SystemPropertiesforHighAvailabilitySystempropertiestoconfigureperiodicacknowledgment(ack).

Thefollowingtableslistattributesthatcanbespecifiedprogrammaticallyorstoredinthe geode.propertiesfiletobereadbyaclient.

GeneralProperties

cache-xml-file

Nameandpathofthefilewhosecontentsareusedbydefaulttoconfigureacacheifoneiscreated.Ifnotspecified,theclientstartswithanemptycache,whichispopulatedatruntime.

nodefault

heap-lru-delta

Thepercentageofentriesthesystemwillevicteachtimeitdetectsthatithasexceededtheheap-lru-limit.Thispropertyisusedonlyifheap-lru-limit isgreaterthan0.

10%

heap-lru-limit

Maximumamountofmemory,inmegabytes,usedbythecacheforallregions.Ifthislimitisexceededby heap-lru-delta percent,LRUreducesthememoryfootprintasnecessary.Ifnotspecified,orsetto0, 0

©CopyrightPivotalSoftwareInc,2013-2019 84 10.0

Page 85: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

memoryusageisgovernedbyeachregion’sLRUentrieslimit,ifany.

conflate-events

Clientsideconflationsetting,whichissenttotheserver. server

connect-timeout

Amountoftime(inseconds)towaitforaresponseafterasocketconnectionattempt.

59

connection-pool-size

Numberofconnectionsperendpoint 5

enable-chunk-handler-thread

Ifthechunk-handler-threadisoperative(enable-chunk-handler=true),itprocessestheresponseforeachapplicationthread.Whenthechunkhandlerisnotoperative(enable-chunk-handler=false),eachapplicationthreadprocessesitsownresponse.

false

disable-shuffling-of-endpoints

Iftrue,preventsserverendpointsthatareconfiguredinpoolsfrombeingshuffledbeforeuse.

false

max-fe-threads

Threadpoolsizeforparallelfunctionexecution.AnexampleofthisistheGetAlloperations.

2*numberoflogicalprocessors

max-socket-buffer-size

Maximumsizeofthesocketbuffers,inbytes,thattheclientwilltrytosetforclient-serverconnections.

65*1024

notify-ack-interval

Interval,inseconds,inwhichclientsendsacknowledgmentsforsubscriptionnotifications.

1

notify-dupcheck-life

Amountoftime,inseconds,theclienttrackssubscriptionnotificationsbeforedroppingtheduplicates.

300

ping-interval

Interval,inseconds,betweencommunicationattemptswiththeservertoshowtheclientisalive.Pingsareonlysentwhenthe ping-intervalelapsesbetweennormalclientmessages.Thismustbesetlowerthantheserver’s maximum-time-between-pings .

10

redundancy-monitor-interval

Interval,inseconds,atwhichthesubscriptionHAmaintenancethreadchecksfortheconfiguredredundancyofsubscriptionservers.

10

tombstone-timeout

Timeinmillisecondsusedtotimeouttombstoneentrieswhenregionconsistencycheckingisenabled. 480000

©CopyrightPivotalSoftwareInc,2013-2019 85 10.0

Page 86: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

LoggingProperties

log-disk-space-limit

Maximumamountofdiskspace,inmegabytes,allowedforalllogfiles,current,androlled.Ifsetto0,thespaceisunlimited.

0

log-fileNameandfullpathofthefilewherearunningclientwriteslogmessages.Ifnotspecified,logginggoesto stdout .

nodefaultfile

log-file-size-limit

Maximumsize,inmegabytes,ofasinglelogfile.Oncethislimitisexceeded,anewlogfileiscreatedandthecurrentlogfilebecomesinactive.Ifsetto0,thefilesizeisunlimited.

0

log-level

Controlsthetypesofmessagesthatarewrittentotheapplication’slog.Thesearethelevels,indescendingorderofseverityandthetypesofmessagetheyprovide:

Error(highestseverity)isaseriousfailurethatwillprobablypreventprogramexecution.

Warningisapotentialprobleminthesystem.

Infoisaninformationalmessageofinteresttotheenduserandsystemadministrator.

Configisastaticconfigurationmessage,oftenusedtodebugproblemswithparticularconfigurations.

Fine,Finer,Finest,andDebugprovidetracinginformation.Onlyusethesewithguidancefromtechnicalsupport.

Enablingloggingatanylevelenablesloggingforallhigherlevels.

config

StatisticsArchivingProperties

statistic-sampling-enabled

Controlswhethertheprocesscreatesastatisticarchivefile. true

statistic-archive-file

Nameandfullpathofthefilewherearunningsystemmemberwritesarchivesstatistics.If archive-disk-space-limit isnotset,theclientappendstheprocessIDtotheconfiguredfilename,likestatArchive-PID.gfs .Ifthespacelimitisset,theprocessIDisnotappendedbuteachrolledfilenameisrenamedtostatArchive-ID.gfs,whereIDistherollednumberofthefile.

./statArchive.gfs

©CopyrightPivotalSoftwareInc,2013-2019 86 10.0

Page 87: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

archive-disk-space-limit

Maximumamountofdiskspace,ingigabytes,allowedforallarchivefiles,current,androlled.Ifsetto0,thespaceisunlimited.

0

archive-file-size-limit

Maximumsize,inmegabytes,ofasinglestatisticarchivefile.Oncethislimitisexceeded,anewstatisticarchivefileiscreatedandthecurrentarchivefilebecomesinactive.Ifsetto0,thefilesizeisunlimited.

0

statistic-sample-rate

Rate,inseconds,thatstatisticsaresampled.Operatingsystemstatisticsareupdatedonlywhenasampleistaken.Ifstatisticarchivalisenabled,thenthesesamplesarewrittentothearchive.

Loweringthesamplerateforstatisticsreducessystemresourceusewhilestillprovidingsomestatisticsforsystemtuningandfailureanalysis.

1

enable-time-statistics

Enablestime-basedstatisticsforthedistributedsystemandcaching.Forperformancereasons,time-basedstatisticsaredisabledbydefault.SeeSystemStatistics .

false

DurableClientProperties

Attribute Description Default

auto-ready-for-events

WhetherclientsubscriptionsautomaticallyreceiveeventswhendeclarativelyconfiguredviaXML.Ifsetto false ,eventstartupisnotautomaticandyouneedtocallthe Cache.ReadyForEvents() methodAPIaftersubscriptionsfortheservertostartdeliveringevents.

true

durable-client-id

Identifiertospecifyifyouwanttheclienttobedurable. empty

durable-timeout

Time,inseconds,adurableclient’ssubscriptionismaintainedwhenitisnotconnectedtotheserverbeforebeingdropped.

300

SecurityProperties

Thetabledescribesthesecurity-relatedsystempropertiesfornativeclientauthenticationandauthorization.

SeeSSLClient/ServerCommunication.

©CopyrightPivotalSoftwareInc,2013-2019 87 10.0

Page 88: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

SystemPropertiesforClientAuthenticationandAuthorization

security-client-auth-factory

Setsthekeyforthe AuthInitialize factoryfunction. empty

security-client-auth-library

Registersthepathtothe securityImpl.dll library. empty

security-client-dhalgo

ReturnstheDiffie-Hellmansecretkeycipheralgorithm. null

security-client-kspath

Pathtoa.PEMfile,whichcontainsthepubliccertificatesforallGeodecacheserverstowhichtheclientcanconnectthroughspecifiedendpoints.

null

ssl-enabled TrueifSSLconnectionsupportisenabled. empty

ssl-keystoreNameofthe.PEMkeystorefile,containingtheclient’sprivatekey.Notsetbydefault.Requiredif ssl-enabled istrue.

ssl-keystore-password

Setsthepasswordfortheprivatekey.PEMfileforSSL. null

ssl-truststore

Nameofthe.PEMtruststorefile,containingtheservers’publiccertificate.Notsetbydefault.Requiredif ssl-enabled istrue.

HighAvailabilityProperties

notify-ack-interval

Minimumperiod,inseconds,betweentwoconsecutiveacknowledgmentmessagessentfromtheclienttotheserver.

10

notify-dupcheck-life

Minimumtime,inseconds,aclientcontinuestotrackanotificationsourceforduplicateswhennonewnotificationsarrivebeforeexpiringit.

300

©CopyrightPivotalSoftwareInc,2013-2019 88 10.0

Page 89: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

ClientCacheXMLReferenceInthistopic

CacheInitializationFile:XMLEssentials

CacheInitializationFileElementDescriptions

Element

Element

ThissectiondocumentstheXMLelementsyoucanusetoconfigureyourGemFirenativeclientapplication.

TodefineaconfigurationusingXML:

1. SetcacheconfigurationparametersinadeclarativeXMLfile.Byconvention,thisuserguidereferstothefileas cache.xml ,butyoucanchooseanyname.

2. SpecifythefilenameandpathtoyourXMLconfigurationfilebysettingthe cache-xml-file propertyinthe geode.properties file.Ifyoudonotspecifypath,theapplicationwillsearchforthefileinitsruntimestartupdirectory.

Forexample:

©CopyrightPivotalSoftwareInc,2013-2019 89 10.0

Page 90: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

cache-xml-file=cache.xml

Whenyourunyourapplication,thenativeclientruntimelibraryreadsandappliestheconfigurationspecifiedintheXMLfile.

ThedeclarativeXMLfileisusedtoexternalizetheconfigurationoftheclientcache.ThecontentsoftheXMLfilecorrespondtoAPIsfoundinthe apache::geode::client packageforC++applications,andtheApache::Geode::Client packagefor.NETapplications.

ElementsaredefinedintheClientCacheXSDfile,named cpp-cache-1.0.xsd ,whichyoucanfindinyournativeclientdistributioninthe xsds directory,andonlineathttps://geode.apache.org/schema/cpp-cache/cpp-cache-1.0.xsd .

CacheInitializationFile:XMLEssentialsThissectionassumesyouarefamiliarwithXML.Whencreatingacacheinitializationfileforyournativeclientapplication,keepthesebasicsinmind:

PlaceanXMLprologatthetopofthefile.Forexample:

<?xmlversion="1.0"encoding="UTF-8"?>

Quoteallparametervalues,includingnumbersandbooleans.Forexample:

concurrency-level="10"caching-enabled="true"

SometypesarespecifictotheGemFirecacheinitializationfile:

Duration:Timespecifiedasanon-negativeintegerandaunit,withnointerveningspace.Therecognizedunitsare h , min , s , ms , us ,and ns .Forexample:

idle-timeout="5555ms"statistic-interval="10s"update-locator-list-interval="5min"

Expiration:Complextypeconsistingofaduration(integer+unit)andanaction,wheretheactionisoneof invalidate , destroy , local-invalidate ,or local-destroy .Forexample:

©CopyrightPivotalSoftwareInc,2013-2019 90 10.0

Page 91: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<expiration-attributestimeout="20s"action="destroy"/><expiration-attributestimeout="10s"action="invalidate"/>

Library:Complextypeconsistingofalibrarynameandafunctionname.Usedbytheclienttoinvokefunctions.Forexample:

<persistence-managerlibrary-name="SqLiteImpl"library-function-name="createSqLiteInstance">

CacheInitializationFileElementDescriptionsThissectionshowsthehierarchyof <client-cache> sub-elementsthatyouusetoconfigureGemFirecachesandclients.Thetop-levelelementinthissyntaxis <client-cache> .

<client-cache> <pool> <locator> <server> <region> <region-attributes> <region-time-to-live>

<region-idle-time>

<entry-time-to-live>

<entry-idle-time>

<partition-resolver>

<cache-loader>

<cache-listener>

<cache-writer>

<persistence-manager>

<pdx>

Inthedescriptions,elementsandattributesnotdesignated“required”areoptional.

<client-cache>ElementThe<client-cache>elementisthetop-levelelementoftheXSDfile.

Yourdeclarativecachefilemustincludeaschemaofthefollowingform:

©CopyrightPivotalSoftwareInc,2013-2019 91 10.0

Page 92: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<client-cachexmlns="http://geode.apache.org/schema/cpp-cache"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://geode.apache.org/schema/cpp-cachehttp://geode.apache.org/schema/cpp-cache/cpp-cache-1.0.xsd"version="1.0">...</client-cache>

Attributesof<client-cache>

Attribute Description

version Required.Mustbe“1.0”

Sub-elementsof<client-cache>

<client-cache> mustcontainatleastoneofthesesub-elements:

Element MinimumOccurrences MaximumOccurrences

<pool> 0 unbounded

<region> 0 unbounded

<pdx> 0 1

<pool>ElementThe<pool>elementisacollectionoftheconnectionsbywhichyourclientapplicationcommunicateswiththeGemFireserver.

Aconnectioncanspecifyeitheralocatororaserver.

A <pool> mustcontainatleastoneconnection,locatororserver,andcancontainmultiplesofeitherorboth.

Sub-elementsof<pool>

A <pool> mustcontainatleastonesub-elementthatspecifiesaconnection,whichcanbeeitheraserveroralocator.Multiplesofeitherorbothtypesarepermitted.

©CopyrightPivotalSoftwareInc,2013-2019 92 10.0

Page 93: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Element MinimumOccurrences MaximumOccurrences

<locator> 0 unbounded

<server> 0 unbounded

Attributesof<pool>

Attribute Description Default

nameString.Required.Nameofthepool,usedwhenconnectingregionstothispool.

free-connection-timeout

Duration.Theamountoftimetowaitforafreeconnectionifmax-connectionsissetandalloftheconnectionsareinuse.

10s

load-conditioning-interval

Duration.Theintervalatwhichthepoolcheckstoseeifaconnectiontoagivenservershouldbemovedtoadifferentservertoimprovetheloadbalance.

5min

min-connections

Non-negativeinteger.Theminimumnumberofconnectionstokeepavailableatalltimes.Whenthepooliscreated,itwillcreatethismanyconnections.If0(zero),thenconnectionsarenotmadeuntilanoperationisperformedthatrequiresclient-to-servercommunication.

1

max-connections

Integer>=-1.Themaximumnumberofconnectionstobecreated.Ifalloftheconnectionsareinuse,anoperationrequiringaclienttoserverconnectionblocksuntilaconnectionisavailable.Avalueof-1meansnomaximum.

-1

retry-attemptsInteger>=-1.Thenumberoftimestoretryanoperationafteratimeoutorexception.Avalueof-1indicatesthatarequestshouldbetriedagainsteveryavailableserverbeforefailing.

-1

idle-timeoutDuration.Setstheamountoftimeaconnectioncanbeidlebeforeitexpires.Avalueof0(zero)indicatesthatconnectionsshouldneverexpire.

5s

ping-interval Duration.Theintervalatwhichthepoolpingsservers. 10s

read-timeoutDuration.Theamountoftimetowaitforaresponsefromaserverbeforetimingoutandtryingtheoperationonanotherserver(ifanyareavailable).

10s

server-groupString.Specifiesthenameoftheservergrouptowhichthispoolshouldconnect.Ifthevalueisnullor""thenthepoolconnectstoallservers.

""

©CopyrightPivotalSoftwareInc,2013-2019 93 10.0

Page 94: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

socket-buffer-size

String.Thesizeinbytesofthesocketbufferoneachconnectionestablished.

32768

subscription-enabled

Boolean.When true ,establishaservertoclientsubscription. false

subscription-message-tracking-timeout

String.Theamountoftimethatmessagessentfromaservertoaclientwillbetracked.Thetrackingisdonetominimizeduplicateevents.Entriesthathavenotbeenmodifiedforthisamountoftimeareexpiredfromthelist.

900s

subscription-ack-interval

String.Theamountoftimetowaitbeforesendinganacknowledgementtotheserverforeventsreceivedfromserversubscriptions.

100ms

subscription-redundancy

String.Setstheredundancylevelforthispool’sserver-to-clientsubscriptions.Aneffortismadetomaintaintherequestednumberofcopies(onecopyperserver)oftheserver-to-clientsubscriptions.Atmost,onecopyperserverismadeuptotherequestedlevel.If0thennoredundantcopiesarekeptontheservers.

0

statistic-interval

Duration.Theintervalatwhichclientstatisticsaresenttotheserver.Avalueof0(zero)meansdonotsendstatistics.

0ms(disabled)

pr-single-hop-enabled

String.When true ,enablesinglehopoptimizationsforpartitionedregions.

true

thread-local-connections

Boolean.Setsthethreadlocalconnectionspolicyforthispool.Whentrue thenanytimeathreadgoestouseaconnectionfromthispoolitwillcheckathreadlocalcacheandseeifitalreadyhasaconnectioninit.Ifsoitwilluseit.Ifnotitwillgetonefromthispoolandcacheitinthethreadlocal.Thisgetsridofthreadcontentionfortheconnectionsbutincreasesthenumberofconnectionstheserverssee.When false thenconnectionsarereturnedtothepoolassoonastheoperationbeingdonewiththeconnectioncompletes.Thisallowsconnectionstobesharedamongmultiplethreadskeepingthenumberofconnectionsdown.

false

multiuser-authentication

Boolean.Setsthepooltousemulti-usersecuremode.Ifinmultiusermode,thenappneedstoget RegionService instanceof Cache .

false

update-locator-list-interval

Duration.Thefrequencywithwhichclientupdatesthelocatorlist.Todisablethissetitsvalueto std::chrono::milliseconds::zero() .

Attribute Description Default

<locator>

©CopyrightPivotalSoftwareInc,2013-2019 94 10.0

Page 95: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<locator> isasub-elementof <pool> thatdefinesaconnectiontoaGemFirelocator,specifiedbyahostandportcombination.

Attributesof<locator>

Attribute Description

host String.Locatorhostname.

port Integerintherange0-65535,inclusive.Locatorportnumber.

Forexample:

<locatorhost="stax01"port="1001"/>

<server><server> isasub-elementof <pool> thatdefinesaconnectiontoaGemFireserver,specifiedbyahostandportcombination.

Attributesof<server>

Attribute Description

host String.Serverhostname.

port Integerintherange0-65535,inclusive.Serverportnumber.

Forexample:

<serverhost="motown01"port="2001"/>

<region>Youcanspecify0ormoreregionsper <client-cache> .Thereisnomaximumlimitonthenumberofregionsa <client-cache> cancontain.

InordertoconnecttoaGemFireserver,aclientapplicationmustdefineatleastoneregionwhosenamecorrespondstothatofaregionontheserver.

©CopyrightPivotalSoftwareInc,2013-2019 95 10.0

Page 96: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

Regionscanbenested.

Sub-elementsof<region>

Usethe <region-attributes> sub-elementtospecifymostofthecharacteristicsofaregion.Regionsmaybenested.

Element MinimumOccurrences MaximumOccurrences

<region-attributes> 0 1

<region> 0 unbounded

Attributesof<region>

Youcanspecifymanyattributestoconfigurearegion,butmostoftheseattributesareencapsulatedinthe <region-attributes> sub-element.The <region> elementitselfhasonlytwoattributes:arequirednameandanoptionalreferenceidentifier.

Attribute Description

name String.Required.

refid String.

<region-attributes>Specify0or1 <region-attributes> elementforeach <region> youdefine.

Ifyouspecifya <region-attributes> element,youmustspecifyatleastoneofthesesub-elements.Whenmorethanonesub-elementisspecified,theymustbedefinedinthisorder:

Element Type MinimumOccurrences MaximumOccurrences

<region-time-to-live> expiration 0 1

<region-idle-time> expiration 0 1

<entry-time-to-live> expiration 0 1

<entry-idle-time> expiration 0 1

<partition-resolver> library 0 1

<cache-loader> library 0 1

©CopyrightPivotalSoftwareInc,2013-2019 96 10.0

Page 97: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<cache-listener> library 0 1

<cache-writer> library 0 1

<persistence-manager> listofproperties 0 1

Element Type MinimumOccurrences MaximumOccurrences

Attributesof<region-attributes>

Attribute Description Default

caching-enabled

Boolean.Iftrue,cachedataforthisregioninthisprocess.Iffalse,thennodataisstoredinthelocalprocess,buteventsanddistributionswillstilloccur,andtheregioncanstillbeusedtoputandremove,etc.

true

cloning-enabled

Boolean.Setscloningonregion. false

scope Enumeration: local , distributed-no-ack , distributed-ack

initial-capacity

String.Setstheinitialentrycapacityfortheregion. 10000

load-factorString.Setstheentryloadfactorforthenext RegionAttributes tobecreated.

0.75

concurrency-level

String.Setstheconcurrencylevelofthenext RegionAttributes tobecreated.

16

lru-entries-limit

String.SetsthemaximumnumberofentriesthiscachewillholdbeforeusingLRUeviction.Areturnvalueofzero,0,indicatesnolimit.Ifdisk-policyisoverflows ,mustbegreaterthanzero.

disk-policyEnumeration: none , overflows , persist .Setsthediskpolicyforthisregion.

none

endpoints String.Alistof servername:port-number pairsseparatedbycommas.

client-notification

Booleantrue/false(on/off) false

pool-nameString.Thenameofthepooltoattachtothisregion.Thepoolwiththespecifiednamemustalreadyexist.

concurrency-checks-enabled

Boolean:true/false.Enablesconcurrentmodificationchecks. true

id String.

refid String.

©CopyrightPivotalSoftwareInc,2013-2019 97 10.0

Page 98: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<region-time-to-live><region-time-to-live>specifieshowlongthisregionremainsinthecacheafterthelastcreateorupdate,andtheexpirationactiontoinvokewhentimerunsout.Acreateorupdateoperationonanyentryintheregionresetstheregion’scounter,aswell.Get(read)operationsdonotresetthecounter.

Usethe <expiration-attributes> sub-elementtospecifydurationandexpirationaction.Theattributesof<expiration-attributes>mustbedefinedinthisorder:

Attribute Description

timeout Duration,specifiedasanintegerandunits.Required.

action Enumeration.Oneof: invalidate , destroy , local-invalidate , local-destroy

<region-idle-time><region-idle-time>specifieshowlongthisregionremainsinthecacheafterthelastaccess,andtheexpirationactiontoinvokewhentimerunsout.Thecounterisresetafteranyaccess,includingcreate,put,andgetoperations.Accesstoanyentryintheregionresetstheregion’scounter,aswell.

Usethe <expiration-attributes> sub-elementtospecifydurationandexpirationaction.Theattributesof<expiration-attributes>mustbedefinedinthisorder:

Attribute Description

timeout Duration,specifiedasanintegerandunits.Required.

action Enumeration.Oneof: invalidate , destroy , local-invalidate , local-destroy

<entry-time-to-live><entry-time-to-live>specifieshowlongthisentryremainsinthecacheafterthelastcreateorupdate,andtheexpirationactiontoinvokewhentimerunsout.Get(read)operationsdonotresetthecounter.

Usethe <expiration-attributes> sub-elementtospecifydurationandexpirationaction.Theattributesof<expiration-attributes>mustbedefinedinthisorder:

Attribute Description

timeout Duration,specifiedasanintegerandunits.Required.

action Enumeration.Oneof: invalidate , destroy , local-invalidate , local-destroy

©CopyrightPivotalSoftwareInc,2013-2019 98 10.0

Page 99: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<entry-idle-time><entry-idle-time>specifieshowlongthisentryremainsinthecacheafterthelastaccess,andtheexpirationactiontoinvokewhentimerunsout.Thecounterisresetafteranyaccess,includingcreate,put,andgetoperations.

Usethe <expiration-attributes> sub-elementtospecifydurationandexpirationaction.Theattributesof<expiration-attributes>mustbedefinedinthisorder:

Attribute Description

timeout Duration,specifiedasanintegerandunits.Required.

action Enumeration.Oneof: invalidate , destroy , local-invalidate , local-destroy

<partition-resolver><partition-resolver>identifiesafunctionbyspecifying library-name and library-function-name .

Apartitionresolverisusedforsingle-hopaccesstopartitionedregionentriesontheserverside.Thisresolverimplementationmustmatchthatofthe PartitionResolver ontheserverside.SeetheAPIClassReference forthePartitionResolverclass.

Forexample:

<partition-resolverlibrary-name="appl-lib"library-function-name="createTradeKeyResolver"/>

<cache-loader><cache-loader>identifiesacacheloaderfunctionbyspecifying library-name and library-function-name .SeetheAPIClassReference fortheCacheLoaderclass.

<cache-listener><cache-listener>identifiesacachelistenerfunctionbyspecifying library-name and library-function-name .SeetheAPIClassReference fortheCacheListenerclass.

©CopyrightPivotalSoftwareInc,2013-2019 99 10.0

Page 100: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

<cache-writer><cache-writer>identifiesacachewriterfunctionbyspecifying library-name and library-function-name .SeetheAPIClassReference fortheCacheWriterclass.

<persistence-manager>Foreachregion,ifthedisk-policyattributeissetto overflows ,apersistence-managerplug-inmustperformcache-to-diskanddisk-to-cacheoperations.SeetheAPIClassReference forthePersistenceManagerclass.

<persistence-manager>identifiesapersistencemanagerfunctionbyspecifying library-name andlibrary-function-name .Youcanalsospecifyasetofpropertiestobepassedtothefunctionasparameters.

Thesub-element <properties> isasequenceof0ormore <property> elements.

Each <property> isaname-valuepair.Wheretheattributesmustbespecifiedinthisorder:

name

value

Forexample:

<region-attributes><persistence-managerlibrary-name="libSqLiteImpl.so"library-function-name="createSqLiteInstance"><properties><propertyname="PersistenceDirectory"value="/xyz"/><propertyname="PageSize"value="65536"/><propertyname="MaxPageCount"value="1073741823"/></properties></persistence-manager></region-attributes>

<pdx>SpecifiestheconfigurationforthePortableDataeXchange(PDX)methodofserialization.

Attributesof<pdx>

Attribute Description

©CopyrightPivotalSoftwareInc,2013-2019 100 10.0

Page 101: Pivotal GemFire® Native Client 10 · 2020-05-05 · What’s New in GemFire Native Client 10.0 GemFire Native Client 10 is based on Apache Geode 1.8. Version 10 is a major release

ignore-unread-fields

Boolean.When true ,donotpreserveunreadPDXfieldsduringdeserialization.Youcanusethisoptiontosavememory.Setthisattributeto true onlyinmembersthatareonlyreadingdatafromthecache.

read-serialized

Boolean.When true ,PDXdeserializationproducesa PdxInstance insteadofaninstanceofthedomainclass.

Attribute Description

©CopyrightPivotalSoftwareInc,2013-2019 101 10.0