vmware gemfire® .net® client 10 · gemfire native client 10.1 release notes what’s new in...
Post on 08-Jul-2020
39 Views
Preview:
TRANSCRIPT
VMwareGemFire®.NET®Client10.1
Rev:10.1.3
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.
2346
1119202325273132363941424448515457616264646567727680858586
TableofContents
TableofContentsVMwareGemFire®NativeClient10.1DocumentationGemFireNativeClient10.1ReleaseNotesSystemRequirementsUpgradingaNativeClientApplicationFromVersion9toVersion10InstallingtheNativeLibraryGettingStartedwiththeNativeLibraryPut/Get/RemoveExampleConfiguringaClientApplicationSystemLevelConfigurationConfiguringtheClientCacheConfiguringRegionsRegisteringInterestforEntriesRegionAttributesSerializingDataVMwareGemFire®PDXSerializationUsingtheVMwareGemFire®PDXAutoserializerUsingtheIPdxSerializableInterfaceIPdxSerializableExampleRemoteQueriesContinuousQueriesSecurity:AuthenticationandEncryptionAuthenticationTLS/SSLClient-ServerCommunicationEncryptionSetUpOpenSSLStartingandstoppingtheclientandserverwithSSLinplaceFunctionExecutionTransactionsSessionStateProviderSystemPropertiesClientCacheXMLReferenceCacheInitializationFile:XMLEssentialsCacheInitializationFileElementDescriptions
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.2 10.1
VMwareGemFire®NativeClient10.1DocumentationPublishedJuly10,2020.
TheVMwareGemFire®NativeClientfor.NETisalibrarythatprovidesaccessforC++andMicrosoft .NET™clientstoaVMwareGemFire®distributedsystem.
SeetheReleaseNotesfornewfeaturesandsupportinformationregardingthisrelease.
UpgradingaNativeClientApplicationFromVersion9toVersion10provideshelpwiththeupgradefromNativeClient9.xtoNativeClient10.x.
SeetheAPIdocsforAPIdetails:
C++APIdocs
.NETAPIdocs
TheApacheGeodecommunityhasahostofexamplesbasedonthelatestC++and.NETAPIs(https://github.com/apache/geode-native/tree/develop/examples ).
SeetheVMwareGemFire®UserGuide forinformationregardingtheserver.
®
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.3 10.1
GemFireNativeClient10.1ReleaseNotes
What’sNewinGemFireNativeClient10.1VMwareGemFire®NativeClient10.1isbasedonApacheGeode1.11.
Version10.1includesanumberofimprovements:
SSLenhancement-supportforcertificatechaining,betterone-waySSLconsistency
CompatibilityissueswithvariousversionsofPCC
Performanceimprovements
Bugfixes.SeeIssuesResolvedinNativeClient10.1
TheApacheGeodecommunityhasahostofexamplesbasedonthelatestC++and.NETAPIs(https://github.com/apache/geode-native/tree/develop/examples ).
IssuesResolvedinNativeClient10.1ThissectiondescribesissuesresolvedinVMwareGemFire®version10.1anditspatchreleases,beginningwiththemostrecentrelease.
IssuesResolvedinNativeClient10.1.3
GEODE-8297,GEMNC-472:Increaseddefaulttimeoutvalueforauthorizationtoaccommodatenetworkswithhigherlatency.
IssuesResolvedinNativeClient10.1.2
GEODE-7930:Endpointnamesarenolongertruncatedto99characters.TheNativeClientnowsupportsendpointnamesthatmeettheRFC2181standardof255charactersforfully-qualifieddomainnames.Thissolutionalsocorrectsaspurious“Failedtoaddendpoint”errorthatwasissuedwhen,infact,noerrorhadoccurred.
IssuesResolvedinNativeClient10.1.1
GEODE-8015,GEMNC-470:Addeddebuggingsymbolstothereleasedlibraries.TheNativeClientrelease
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.4 10.1
forWindowsnowincludesa.pdbsymbolfile.OnLinux,thesymbolsarenowembeddedinthesharedlibrary(.sofile).
IssuesResolvedinNativeClient10.1.0
GEODE-3415:AddedsupportforcertificatechainfilesinSSLconfiguration.
GEODE-7437:Enforcedrecognitionoftruststoreinone-waySSL.
GEODE-5708,GEMNC-465:Fixedanissuewithanoverly-aggressivememoryfree-upoperationinpartitionedregionsthatcausedtheputAll()operationtofailwhencalledasecondtimeduetoaclosedserverconnection.
GEODE-6576:Improvedhandlingofstaleconnectionstopartitionedregions.
GEODE-6624,GEMNC-438:Improvedhandlingofdataserializationerrorreportingbyfixingaproblemcausedbynestedexceptions.
GEODE-6800,GEMNC-448:FixedagcccompilationerrorrelatedtoCacheableFileNameobjects.
GEODE-6835,GEMNC-442:Addedretrylogictopreventspuriousserver-sideSecurityManagererrors.
GEODE-7019:Fixclosingofidleconnectionsinnativeclient.
GEODE-7061:Reducedthenumberofconnectionscreatedduringhighloadconditionswithmanythreads.
GEODE-7299:FixedamemoryleakassociatedwithPDXdataserialization.
GEODE-7316:Fixedaraceconditionthatcouldcauseaclientapptocrashonshutdown.
GEODE-7418,GEMNC-464:FixedanissuewithPDXserialization/deserializationofJSONobjects.
GEODE-7476,GEODE-7509,GEMNC-436:Fixedamemoryleakthatappearedduringrepeatedqueries.
GEODE-7783:Optimizedconnectionhandlingtoimproveperformance.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.5 10.1
SystemRequirementsInthistopic
GemFireCompatibility
ApplicationCompatibility
.NETCompatibility
HostMachineRequirements
WindowsSupport
LinuxSupport
PCFSupport
SoftwareRequirementsforUsingSSL
TheVMwareGemFire®nativeclientprovidesaccessforC++andMicrosoft®.NET™clientstotheVMwareGemFire®distributedsystem.ItoperatesonplatformsrunningMicrosoftWindows,Linux(Intel),andPivotalCloudFoundry.
GemFireCompatibilityTheGemFireNativeClientsupportsapplicationsthatcommunicatewithGemFireservers.NativeClientversion10.1workswithPivotalGemFireversions9.0.0andlater.
ThefollowingtableshowswhichversionsoftheNativeClientarecompatiblewiththevariousversionsoftheGemFireserver.
GemFireNativeClientVersion GemFireServerVersion
GemFireNativeClient10 GemFireServer10
GemFireNativeClient10GemFireNativeClient9.1,9.2
GemFireServer9.x
GemFireNativeClient9.1GemFireNativeClient8.2
GemFireServer8.2
ApplicationCompatibilityGemFireNativeClientiscompiledusing64-bitarchitecturesforalloperatingsystems.Linkingwith32-bit
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.6 10.1
applicationsisnotsupported.
SupportedPlatforms:C++ClientTheGemFireNativeClientsupportsapplicationsthatruninthefollowingclientenvironments:
Platform Version
Linux RedHatEnterpriseLinux(RHEL)7
Linux Ubuntu16(Xenial)
WindowsDesktop 10
WindowsServer 2016
PivotalCloudFoundry PCF2.3.2+
SupportedPlatforms:.NETClient
Platform Version
WindowsDesktop 10
WindowsServer 2016
PivotalCloudFoundry PCF2.3.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:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.7 10.1
Logsthatareusefulfortroubleshooting.Synchronizedtimestampsensurethatlogmessagesfromdifferenthostscanbemergedtoreproduceanaccuratechronologicalhistoryofadistributedrun.Aggregateproduct-levelandapplication-leveltimestatistics.Accuratemonitoringofthesystemwithscriptsandothertoolsthatreadthesystemstatisticsandlogfiles.
Thehostnameandhostfilesareproperlyconfiguredforthemachine.
WindowsSupportForWindowsC++applications,theGemFireNativeClientlibrary, pivotal-gemfire.dll ,requirestheMicrosoftVisualC++2017RedistributablePackage,whichyoucanfindontheVisualStudio2017webpage .Scrolldownto“RedistributablesandBuildTools”andselect“MicrosoftVisualC++RedistributableforVisualStudio2017”,andbesuretoselectthe“x64”version.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
ManydefaultLinuxinstallationsuseSYNcookiestoprotectthesystemagainstmaliciousattacksthat
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.8 10.1
floodTCPSYNpackets.TheuseofSYNcookiesdramaticallyreducesnetworkbandwidth,andcanbetriggeredbyarunningVMwareGemFire®distributedsystem.
TodisableSYNcookiespermanently:
1. Editthe /etc/sysctl.conf filetoincludethefollowingline:
net.ipv4.tcp_syncookies=0
SettingthisvaluetozerodisablesSYNcookies.
2. Reload sysctl.conf :
$sysctl-p
PCFSupportPivotalCloudFoundrysupports.NETandC++nativeclientapplications.
PCFversions2.3.2andhigherincludetheMicrosoftVS2017C++RedistributableDLLs.
PCF.NETRequirements
PCF2.3.2ornewer
WindowsServer2016
.NET4.5.2ornewer
Torunyourcloudnative.NETapplicationonPCF:
1. The Pivotal.GemFire.dll mustbeinthe output folderofyour.NETproject.
2. Rebuildyourapplication.
3. FromVisualStudio,publishyourapplicationtoafilesystem.
4. Fromwithinthepublishedfilesystem,use cf push todeployyourapplicationtoPCFasyouwouldother.NETapplications.
PCFC++Requirements
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.9 10.1
PCF2.3.2ornewer
UbuntuorWindows2017stemcells
TorunyourcloudnativeC++applicationonPCF:
1. Theruntimelibraries pivotal-gemfire.dll and cryptoImpl.dll mustbeinthepathofyourC++application.
2. Use cf push todeployyourapplicationtoPCFasyouwouldotherC++applications.
SoftwareRequirementsforUsingSSLIfyouplanonusingSSLinyourVMwareGemFire®nativeclientandserverdeployment,youwillneedtodownloadandinstallOpenSSL.TheVMwareGemFire®nativeclientrequiresOpenSSLversion1.1.1.
ForWindowsplatforms,youcanuseeithertheregularortheOpenSSL“Light”version.
Inaddition,makesurethatyoursystemenvironmentvariableshavebeenconfiguredtoincludeOpenSSL.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.10 10.1
UpgradingaNativeClientApplicationFromVersion9toVersion10GemFireNativeClientVersion10introducesbreakingchangesforVersion9applications.Updatingyourclientapplicationswillrequiremoreinterventionthanmerelyrecompiling.
Ingeneral,youwillhavebestperformanceandreliabilityifclientsandserversbothrunthelatestversionsoftheirrespectivesoftware.
GemFireserverandclientsoftwarereleasesfollowsimilarnumberingschemes,buttheyarenotreleasedinlockstep.ThefollowingdiagramillustratestheinteroperabilitybetweenrecentversionsofGemFireserversoftwareandGemFireNativeClientsoftware.
OverviewofChangesVMwareGemFire®NativeClientimprovementsandnewfeaturesinclude:
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 ).
ForexamplesofsourcechangesseetheNativeClient9toNativeClient10UpgradeSample .
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.11 10.1
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”intotheVMwareGemFire®Javaserver.ThisisnowmanagedthroughaCacheinstance.
Anoteto.NETusersoftheNativeClient:userscanpassinaninstanceoftheirauthorizationclassintotheCacheFactory( CacheFactory.SetAuthInitialize(app_auth); ).
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.12 10.1
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
Propertiesuse std::unordered map
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.13 10.1
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
Cache::createDataInput/Output returnsvalue
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.14 10.1
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
PoolFactory
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.15 10.1
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
HashMapOfSharedBase Replacewithstd::hash
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.16 10.1
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.
RegionAttributesFactory ReplacesAttributesFactory
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.17 10.1
RegionShortcut Enumclassholdingallregiontypes(PROXY,CACHING_PROXY,CACHING_PROXY_ENTRY_LRU,LOCAL_ENTRY_LRU)
TypeRegistry Classforregisteringacustomserializabletype.
NeworRenamedClass SummaryofChanges
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.18 10.1
InstallingtheNativeLibraryInstallthenativeclientbyextractingthecontentsofthedistributionarchiveandsettinguptheenvironment.
InstallationPrerequisites
BeforeinstallingtheGemFirenativeclient,confirmthatyoursystemmeetsthehardwareandsoftwarerequirementsdescribedinGemFireNativeClientSystemRequirements.
CopyandUncompresstheDistributionArchive
1. Inabrowser,navigatetothePivotalGemFiredownloadpage .
2. FromtheReleases:pull-downmenu,selectthemostrecentversionofVMwareGemFire®NativeClient.
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 .
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.19 10.1
GettingStartedwiththeNativeLibraryInthistopic
SetUpYourDevelopmentEnvironment
EstablishAccesstoaVMwareGemFire®ClusterConnectingtotheServer
ApplicationDevelopmentWalkthrough
ProgrammingExamples
TousetheVMwareGemFire®NativeLibraryfordevelopingVMwareGemFire®clientapplications:
ObtainadistributionoftheNativelibraryandinstallitonyourdevelopmentplatform.
Setupyourdevelopmentenvironmentwiththetoolsyouneed,suchasacompilerandanOpenSSLsecuritylibrary.
EstablishaccesstoaneworexistingVMwareGemFire®cluster.
WriteyourclientapplicationusingtheVMwareGemFire®nativelibrarytointeractwiththeVMwareGemFire®server.
SetUpYourDevelopmentEnvironmentYouwillneedsomeessentialtools,suchasacompilerandalinker.YourcompilermusthaveaccesstotheNativeClientheaderfiles,andthelinkermusthaveaccesstotheNativeClientlibraries.TheheaderfilesandlibrariesarelocatedintheNativeClientinstallationdirectory.
EstablishAccesstoaVMwareGemFire®ClusterAsyoudevelopyourapplication,youwillneedaccesstoaVMwareGemFire®cluster.YourclientapplicationconnectstoaVMwareGemFire®clusterbyspecifyingtheaddress(hostnameorIPaddress)andportnumberofoneormorelocators,andthenameofaregionthatalsoexistsonthecluster.TheclientAPIestablishesapoolofthesenetworkconnectionsforyourclientapplicationtouse.
Youcanchoosewhethertousealarge,remote,production-qualitycluster;asmall,local,developmentcluster;orsomethingin-between,suchasatestingorexperimentallabinstallation.
IntheVMwareGemFire®User’sGuide,seeConfiguringandRunningaCluster andClient/ServerConfiguration
forinstructionsonsettingupandstartingtheclusterforaclient/serverconfiguration.
ConnectingtotheServer
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.20 10.1
Toconnecttoaserver,yourapplicationmustfollowthesesteps:
1. Instantiatea CacheFactory ,settingcharacteristicsofinterest(forexample, log-level ).
2. Createacacheanduseittoinstantiatea PoolFactory ,specifyingthehostnameandportfortheserverlocator.
3. Createanamedpoolofnetworkconnections.
4. Instantiatearegionofthedesiredtype(usuallyCACHING_PROXYorPROXY)andconnectitbynametoitscounterpartontheserver.
Oncetheconnectionpoolandthesharedregionareinplace,yourclientapplicationisreadytosharedatawiththeserver.
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
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
SeetheVMwareGemFire®UserGuidesectionConfiguringaClient/ServerSystem formoredetails.
ApplicationDevelopmentWalkthrough
The.NETAppDevelopmentWalkthrough describeshowtosetupanativeclientdevelopmentenvironmentusingCMake.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.21 10.1
ProgrammingExamplesTheVMwareGemFire®ClientbuildprovidesasetofprogrammingexamplestohelpyouunderstandtheclientAPI.The examples directorycontainsCMakefilesanda cpp subdirectorycontainingC++examples.TheWindowsbuildalsoincludesa dotnet subdirectorycontainingC#examples.
CMakefilesarelocatedateachlevelofthedirectorystructuretoallowexamplestobebuiltindividuallyoringroups.
Thedirectorystructureresemblesthishierarchy(someentriesareomittedforclarity):
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/RemoveExampleforsamplecodeshowingthebasicsofhowaclientapplicationconnectstoaVMwareGemFire®clusterandperformsbasicoperationsonaremoteserver.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.22 10.1
Put/Get/RemoveExampleInthistopic
Put/Get/RemoveExampleCode
Thenativeclientreleasecontainsanexamplewrittenfor.NETshowinghowaclientapplicationcanestablishaconnectiontoaclusterandthenusethatconnectiontoperformbasicoperationsonaremoteserver.Theexampleislocatedin ../examples/dotnet/putgetremove .
Theexampleperformsasequenceofoperations,displayingsimplelogentriesastheyrun.
Toruntheexample,followtheinstructionsinthe README.md fileintheexampledirectory.
Reviewthesourcecodeintheexampledirectorytoseeexactlyhowitoperates.
Beginbyrunningascriptthatsetsuptheserver-sideenvironmentbyinvoking gfsh commandstocreatearegion,simplycalled“example_userinfo.”
Runtheexampleclientapplication,whichperformsthefollowingsteps:
ConnectstotheserverPerformsregionputoperationsusingkey/valuepairsUsesregiongettoretrievethevaluesUsesregionremovetoremovethevalues
Put/Get/RemoveExampleCodeThissectioncontainscodesnippetsshowinghighlightsofthe.NETput/get/removeexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.
The.NETexamplecreatesacache,thenusesittocreateaconnectionpoolandaregionobject(ofclassIRegion ).
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.23 10.1
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");}
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.24 10.1
ConfiguringaClientApplicationInthistopic
ProgrammaticConfigurationvsXMLConfiguration
HighAvailabilitywithServerRedundancy
Youcanconfigureyournativeclientapplication:
Programmaticallyinyourappcode
ViaXMLfilesandpropertiesfiles(seeClientCacheXMLReference)
Throughacombinationofprogrammaticandfile-basedapproaches
Thissectiondescribesconfigurationontwolevels,thesystemlevelandthecachelevel.Systempropertysettingsdescribeyourapplication’sbehavior,whilecacheconfigurationdescribesdata.
ProgrammaticConfigurationvsXMLConfigurationProgrammaticconfigurationenablesyourclientapplicationtodynamicallyadapttochangingruntimeconditions.
Incontrast,XMLconfigurationexternalizesproperties,suchaslocatoraddressesandpoolconnectiondetails,sotheycanbechangedwithoutrequiringthatyourecompileyourapplication.
TablesofpropertiesSeeSystemPropertiesforalistofsystempropertiesthatcanbeconfiguredprogrammaticallyorinthegeode.properties file.
HighAvailabilitywithServerRedundancyWhenredundancyisenabled,secondaryserversmaintainqueuebackupswhiletheprimaryserverpusheseventstotheclient.Iftheprimaryserverfails,oneofthesecondaryserversstepsinasprimarytoprovideuninterruptedeventmessagingtotheclient.Toconfigurehighavailability,setthesubscription-redundancy intheclient’spoolconfiguration.Thissettingindicatesthenumberofsecondaryserverstouse.SeetheVMwareGemFire®UserGuidesectionConfiguringHighlyAvailableServers for
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.25 10.1
moredetails.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.26 10.1
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.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.27 10.1
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-fileattributein geode.properties (seeSystemProperties).Ifthe cache.xml isnotfound,theprocessstartswithanunconfiguredcache.
UsingtheDefaultSampleFile
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.28 10.1
Asample geode.properties fileisincludedwiththeVMwareGemFire®nativeclientinstallationinthenative-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
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.29 10.1
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.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.30 10.1
ConfiguringtheClientCacheClientcachesprovidetheframeworkforclientstostore,manage,anddistributeapplicationdata.
AcacheisanentrypointforaccesstoVMwareGemFire®.Throughthecache,clientsgainaccesstotheVMwareGemFire®cachingframeworkfordataloading,distribution,andmaintenance.
A Cache instanceallowsyourclienttosetgeneralparametersforcommunicationbetweenacacheandothercachesinthedistributedsystem,andtocreateandaccessanyregioninthecache.
Regionsarecreatedfrom Cache instances.Regionsprovidetheentrypointstotheinterfacesforinstancesof Region and RegionEntry .
Formoreinformationspecifictoyourclientprogramminglanguage,seethe.NETClientAPI .
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.31 10.1
ConfiguringRegionsInthistopic
ProgrammaticRegionCreation
DeclarativeRegionCreation
InvalidatingandDestroyingRegions
RegionAccess
GettingtheRegionSize
TheregionisthecorebuildingblockoftheVMwareGemFire®distributedsystem.Allcacheddataisorganizedintodataregionsandyoudoallofyourdataputs,gets,andqueryingactivitiesagainstthem.
InordertoconnecttoaVMwareGemFire®server,aclientapplicationmustdefinearegionthatcorrespondstoaregionontheserver,atleastinname.SeeDataRegions intheVMwareGemFire®UserGuidefordetailsregardingserverregions,andRegionAttributesinthisguideforclientregionconfigurationparameters.
Youcancreateregionseitherprogrammaticallyorthroughdeclarativestatementsina cache.xml file.Programmaticconfigurationisrecommended,asitkeepstheconfigurationcloseathandandeliminatesanexternaldependency.Regioncreationissubjecttoattributeconsistencychecks.
ProgrammaticRegionCreationTocreatearegion:
1. Instantiatea CacheFactory anduseittocreateacache.
2. Thecacheincludesaninstanceof PoolManager —useittocreateaconnectionpool.
3. Usecachetoinstantiatea RegionFactory anduseittocreatearegion,specifyinganydesiredattributesandanassociationwiththeconnectionpool.
.NETC#RegionCreationExample
ThisexampleillustrateshowtocreateapairofregionsusingC#:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.32 10.1
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:
<?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-
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.33 10.1
cache/cpp-cache-1.0.xsd .
InvalidatingandDestroyingRegionsInvalidationmarksallentriescontainedintheregionasinvalid(withnullvalues).Destructionremovestheregionandallofitscontentsfromthecache.
Youcanexecutetheseoperationsexplicitlyinthelocalcacheinthefollowingways:
ThroughdirectAPIcallsfromtheclientusingApache::Geode::Client::IRegion<TKey, TValue >::InvalidateRegion() .
Throughexpirationactivitiesbasedontheregion’sstatisticsandattributesettings.
Ineithercase,youcanperforminvalidationanddestructionasalocaloradistributedoperation.
Alocaloperationaffectstheregiononlyinthelocalcache.
Adistributedoperationworksfirstontheregioninthelocalcacheandthendistributestheoperationtoallothercacheswheretheregionisdefined.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
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.34 10.1
whitespace spaceortab
anglebrackets <>
colon :
quote "
forwardslashandbackslash /\
pipe(verticalbar) |
questionmark ?
asterisk *
IneligibleCharacterdescription IneligibleCharacter
GettingtheRegionSizeThe Region APIprovidesa Size propertythatgetsthesizeofaregion.Forclientregions,thisgivesthenumberofentriesinthelocalcache,notontheservers.Seethe Region APIdocumentationfordetails.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.35 10.1
RegisteringInterestforEntriesForclientregions,youcanprogrammaticallyregisterinterestinentrykeysstoredonacacheserverregion.Aclientregionreceivesupdatenotificationsfromthecacheserverforthekeysofinterest.
Youcanregisterinterestforspecificentrykeysorforallkeys.Regularexpressionscanbeusedtoregisterinterestforkeyswhosestringsmatchtheexpression.Youcanalsounregisterinterestforspecifickeys,groupsofkeysbasedonregularexpressions,orforallkeys.
Note:Interestregistrationandunregistrationaresymmetricaloperations.Consequently,youcannotregisterinterestinallkeysandthenunregisterinterestinaspecificsetofkeys.Also,ifyoufirstregisterinterestinspecifickeyswith registerKeys ,thencall registerAllKeys ,youmustcall unregisterAllKeys beforespecifyinginterestinspecifickeysagain.
ClientAPIforRegisteringInterestYouregisterclientinterestthroughthe.NETAPI.The.NETAPIprovidesthe RegisterKeys , RegisterAllKeys ,and RegisterRegex methods,withcorrespondingunregistrationaccomplishedusingthe UnregisterKeys ,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.Toreduceresourceusage,aclientexpirestrackedsourcesforwhichnewnotificationshavenotbeenreceivedforaconfigurableamountoftime.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.36 10.1
NotificationSequence
Notificationsinvoke CacheListeners ofcachelessclientsinallcasesforkeysthathavebeenregisteredontheserver.Similarly,invalidatesreceivedfromtheserverinvoke CacheListeners ofcachelessclients.
Ifyouregistertoreceivenotifications,listenercallbacksareinvokedirrespectiveofwhetherthekeyisintheclientcachewhena destroy or invalidate eventisreceived.
RegisteringInterestforSpecificKeysYouregisterandunregisterinterestforspecifickeysthroughthe registerKeys and unregisterKeysfunctions.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();
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.37 10.1
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.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.38 10.1
RegionAttributesRegionattributesgoverntheautomatedmanagementofaregionanditsentries.
Regionattributesettingsdeterminewherethedataresides,howtheregionismanagedinmemory,andtheautomaticloading,distribution,andexpirationofregionentries.
SpecifyingRegionAttributesSpecifyregionattributesbeforecreatingtheregion.YoucandothiseitherthroughtheAPIorthroughthedeclarativeXMLfile.TheAPIincludesclassesfordefiningaregion’sattributesbeforecreationandformodifyingsomeattributesaftercreation.Fordetails,seetheAPIfor RegionShortcut , RegionAttributes ,RegionAttributesFactory ,and AttributesMutator .
RegionShortcutsVMwareGemFire®providespredefined,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
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.39 10.1
storesdataintheclientcacheanddoesnotconnecttheregiontotheservers.Thisisaclient-side-onlyregion.Limitstheamountofdatastoredlocallyintheclienttoadefaultlimitof100,000entriesbyejectingtheleastrecentlyused(LRU)entries.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.40 10.1
SerializingDataDatainyourclientapplication’sVMwareGemFire®cachemustbeserializabletobesharedwithVMwareGemFire®serversandotherVMwareGemFire®clients.Built-in.NETtypesareserializedautomaticallyintothecacheandcanberetrievedbyJavaserversandotherVMwareGemFire®clients.
Fordomainobjectsthatarenotsimpletypes,VMwareGemFire®providesmultipleserializationoptionsforstorageandtransmittalbetweenprocesses,ofwhichVMwareGemFire®PortableDataeXchange(PDX)serializationoffersthebestcombinationofversatilityandease-of-useformostapplications.
Many.NETclientscantakeadvantageofPDXreflection-basedautoserialization.
Tolearnmoreaboutotherserializationoptions,seetheDataSerializationsectionintheVMwareGemFire®UserGuide .
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.41 10.1
VMwareGemFire®PDXSerializationInthistopic
PortabilityofPDXSerializableObjects
ReducedDeserializationofSerializedObjects
DeltaPropagationwithPDXSerialization
PDXSerializationDetails
VMwareGemFire®’sPortableDataeXchange(PDX)isacross-languagedataformatthatcanreducethecostofdistributingandserializingyourobjects.
VMwareGemFire®.NETPDXserialization:
IsinteroperablewithotherlanguagesbyVMwareGemFire®–noneedtoprogramaJava-sideimplementation
Reducesdeserializationoverheadbyprovidingdirectfieldaccessonserversofserializeddata,withoutfulldeserialization.Storesdatainnamedfieldsthatyoucanaccessindividually,toavoidthecostofdeserializingtheentiredataobject
WorkswithVMwareGemFire®deltapropagation
ThesimplestoptionistouseautomaticserializationbyregisteringtheVMwareGemFire®.NETPDXreflection-basedautoserializerinyourapplication.Whenyouhaveanautoserializer,VMwareGemFire®usesitforalldomainobjectsthatarenotseparatelytreatedundertheIPDXSerializableinterface.
Forgreatercontrol,youcanspecifyindividualtreatmentfordomainobjectsusingthe IPdxSerializableinterface.Objectsderivedfromthe IPdxSerializable interfacearenotsubjecttoautoserialization.
PortabilityofPDXSerializableObjectsWhenyoucreatean IPdxSerializable object,VMwareGemFire®storestheobject’stypeinformationinacentralregistry.Theinformationispassedbetweenpeers,betweenclientsandservers,andbetweendistributedsystems.
Thisoffersanotableadvantagetothe.NETclient,whichsharesdatawithJavacacheservers.WhenusingPDXserialization,clientsautomaticallypassregistryinformationtoserverswhentheystoreanIPdxSerializable object.Clientscanrunqueriesandfunctionsagainstthedataintheserverswithouttheserversneedingtoknowanythingaboutthestoredobjects.Oneclientcanstoredataontheservertobe
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.42 10.1
retrievedbyanotherclient,withtheserverneverneedingtoknowtheobjecttype.Thismeansyoucancodeyour.NETclientstomanagedatausingJavaserverswithouthavingtocreateJavaimplementationsofyour.NETdomainobjects.
ReducedDeserializationofSerializedObjectsTheaccessmethodsfor IPdxSerializable objectsallowyoutoexaminespecificfieldsofyourdomainobjectwithoutdeserializingtheentireobject.Thiscanreducedeserializationcostssignificantly.Client.NETappscanrunqueriesandexecutefunctionsagainsttheobjectsintheservercacheswithoutdeserializingtheentireobjectontheserverside.ThequeryengineautomaticallyrecognizesPDXobjectsandusesonlythefieldsitneeds.
ClientscanexecuteJavafunctionsonserverdatathatonlyaccesspartsofthedomainobjectsbyusingPdxInstance.
Likewise,peerscanaccessjustthefieldsneededfromtheserializedobject,keepingtheobjectstoredinthecacheinserializedform.
DeltaPropagationwithPDXSerializationYoucanuseVMwareGemFire®deltapropagationwithPDXserialization.
PDXSerializationDetailsSeethefollowingsectionsfordetailsonimplementingPDXserializationandautoserialization:
UsingtheVMwareGemFire®Autoserializer
UsingtheIPdxSerializableInterface
IPdxSerializableExample
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.43 10.1
UsingtheVMwareGemFire®PDXAutoserializerInthistopic
JavaInteroperabilitywith.NETSpecificTypes
RemoteQueriesof.NETOnlyTypes
ExtendingthePDXAutoserializer
It’sextremelyeasyfor.NETapplicationstostoreandretrievedatafromGeode.Allthat’srequiredisasinglelineofcodetosetthe PdxSerializer tothe.NETclient’s ReflectionBasedAutoSerializer :
cache.TypeRegistry.PdxSerializer=newReflectionBasedAutoSerializer();
(Theautoserializercanberegisteredonlyintheapplicationcode.Itcannotbeconfigureddeclarativelyincache.xml .)
Afteranautoserializerhasbeenregistered,alluserclassescanautomaticallybestoredwithoutneedingtoimplementanyinterfaces.Forexample,thefollowing put commandstores value ,whichisaninstanceofauserdefinedclass,intheregion.
region.put(key,value);
The.NETclient’s ReflectionBasedAutoSerializer supportsthefulllistof.NETprimitivesandothercommonbuilt-intypes.
Typeswithoutano-argconstructorarenotsupportedbythe ReflectionBasedAutoSerializer .Thisincludesalluserdefinedstructs. System.Data.Datatable isanexampleofasystemclassthatisnotsupportedduetolackofano-argconstructor.
JavaInteroperabilitywith.NETSpecificTypesJavadoesnothaveunsigneddatatypesorexactequivalentsof Guid and Decimal .Careshouldbetakenwhenpassingthesetypesbetween.NETandJavaapplicationsusingthe.NETReflectionBasedAutoSerializer .Forexample,ifstoring UInt16 data(thatis,16-bitunsignedvalues),beawarethatvaluesgreaterthan UInt16.MaxValue/2-
1willshowupasnegativenumbersinJava.Usingthatdata
inaJavaapplicationmayhaveunexpectedbehavior.Ifyouexpecttoexceedhalftherangeforthegiven
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.44 10.1
type( Byte.MaxValue/2 , UInt16.MaxValue/2 , UInt32.MaxValue/2 ,or UInt64.MaxValue/2 )youshouldusethenextlargertype.Thisobviouslybreaksdownfor UInt64 ,whichhasnonextlargertype.However,ifyourrangeexceeds UIn64.MaxValue/2 ,youlikelyhaveamuchmorecomplexsetofissuestodealwith,suchasheavypagingduetosuchalargedataset.
RemoteQueriesof.NETOnlyTypesAtthistimethe.NETClientdoesnotsupportqueriesagainstuserclassesthathavebeenstoredontheserverusingthe ReflectionBasedAutoSerializer .
Whenyouregisterthereflection-basedserializer,VMwareGemFire®usesittoserializeallobjectsthatdonotimplement IPdxSerializable .Youcancustomizetheauto-serializationbehaviorforyourdomainobjectsbyaddingserializationattributestoyourobject’sfields.
ExtendingthePDXAutoserializerForeachobjectyouintendtohaveautoserialized,youcancustomizetheserializationasneeded.
Note:IfyoualsousePDXserializationinJavafortheobject,customizeyourserializationinthesamewayforbothlanguages.
Thefollowingextensionmethodsapplytoautoserialization:
WriteTransform.Controlswhatfieldvalueiswrittenduringautoserialization.
ReadTransform.Controlswhatfieldvalueisreadduringautodeserialization.
GetFieldType.Definesthespecificfieldnamesthatwillbegeneratedduringautoserialization.
IsIdentityField.Controlswhichfieldismarkedastheidentityfield.IdentityfieldsareusedwhenaPdxInstance computesitshashcodetodeterminewhetheritisequaltoanotherobject.
GetFieldType.Determinesthefieldtypethatwillbeusedwhenautoserializingthegivenfield.
IsFieldIncluded.Specifieswhichfieldsofaclasstoautoserialize.
Tospecifyanidentifierfieldinyourdomainobject,addtheattribute PdxIdentityField tothefield.
Forexample:
[PdxIdentityField]privateintid;
Toexcludeafieldfromserialization,addthe.NETattribute NonSerialized tothefield.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.45 10.1
Forexample:
[NonSerialized]privateintmyLocalData;
ForeachdomainclassVMwareGemFire®serializesusingtheautoserializer,allfieldsareconsideredforserializationexceptthosedefinedas static , literal or readonly andthoseyouexplicitlyexcludeusingthe.NET NonSerialized attribute.
Thisexamplecodedemonstrateshowtoextendtheautoserializertocustomizeserialization.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.46 10.1
publicclassAutoSerializerEx:ReflectionBasedAutoSerializer{publicoverrideobjectWriteTransform(FieldInfofi,Typetype,objectoriginalValue){if(fi.FieldType.Equals(Type.GetType("System.Guid"))){returnoriginalValue.ToString();}elseif(fi.FieldType.Equals(Type.GetType("System.Decimal"))){returnoriginalValue.ToString();}elsereturnbase.WriteTransform(fi,type,originalValue);}
publicoverrideobjectReadTransform(FieldInfofi,Typetype,objectserializeValue){if(fi.FieldType.Equals(Type.GetType("System.Guid"))){Guidg=newGuid((string)serializeValue);returng;}elseif(fi.FieldType.Equals(Type.GetType("System.Decimal"))){returnConvert.ToDecimal((string)serializeValue);}elsereturnbase.ReadTransform(fi,type,serializeValue);}
publicoverrideFieldTypeGetFieldType(FieldInfofi,Typetype){if(fi.FieldType.Equals(Type.GetType("System.Guid"))||fi.FieldType.Equals(Type.GetType("System.Decimal")))returnFieldType.STRING;returnbase.GetFieldType(fi,type);}
publicoverrideboolIsIdentityField(FieldInfofi,Typetype){if(fi.Name=="_identityField")returntrue;returnbase.IsIdentityField(fi,type);}
publicoverridestringGetFieldName(FieldInfofi,Typetype){if(fi.Name=="_nameChange")returnfi.Name+"NewName";returnfi.Name;}
publicoverrideboolIsFieldIncluded(FieldInfofi,Typetype){if(fi.Name=="_notInclude")returnfalse;returnbase.IsFieldIncluded(fi,type);}}
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.47 10.1
UsingtheIPdxSerializableInterfaceWhenyouwriteobjectsusingPDXserialization,theyaredistributedtotheservertierinPDXserializedform.Whenyourunqueriesagainsttheobjectsontheservers,onlythefieldsyouspecifyaredeserialized.
UsethisproceduretoprogramyourdomainobjectforPDXserializationusingthe IPdxSerializableInterface.
1. Inyourdomainclass,implement Apache.Geode.Client.IPdxSerializable .Example:
usingApache.Geode.Client;...publicclassPortfolioPdx:IPdxSerializable
2. Ifyourdomainclassdoesnothaveazero-argconstructor,createoneforit.IfyoualsousePDXserializationinJavafortheobject,serializetheobjectinthesamewayforeachlanguage.Serializethesamefieldsinthesameorderandmarkthesameidentifyfields.
3. Programthe IPdxSerializableToData functiontoserializeyourobjectasrequiredbyyourapplication.
a. Writeyourdomainclass’sstandard.NETdatafieldsusingthe IPdxWriter writemethods.VMwareGemFire®automaticallyprovides IPdxWriter tothe ToData functionforIPdxSerializable objects.
b. Callthe ToDatamarkIdentifyField functionforeachfieldVMwareGemFire®shouldusetoidentifyyourobject.Thisisusedtocompareobjectsforoperationslike DISTINCT queries.ThemarkIdentifyField callmustcomeaftertheassociatedfieldwritemethods.Example:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.48 10.1
//objectfieldsprivateintm_id;privatestringm_pkid;privatePositionPdxm_position1;privatePositionPdxm_position2;privateHashtablem_positions;privatestringm_type;privatestringm_status;privatestring[]m_names;privatebyte[]m_newVal;privateDateTimem_creationDate;privatebyte[]m_arrayZeroSize;privatebyte[]m_arrayNull;//ToDatapublicvoidToData(IPdxWriterwriter){writer.WriteInt("id",m_id)//identityfield.MarkIdentityField("id").WriteString("pkid",m_pkid).WriteObject("position1",m_position1).WriteObject("position2",m_position2).WriteObject("positions",m_positions).WriteString("type",m_type).WriteString("status",m_status).WriteStringArray("names",m_names).WriteByteArray("newVal",m_newVal).WriteDate("creationDate",m_creationDate).WriteByteArray("arrayNull",m_arrayNull).WriteByteArray("arrayZeroSize",m_arrayZeroSize);}
4. Program IPdxSerializableFromData toreadyourdatafieldsfromtheserializedformintotheobject’sfieldsusingthe IPdxReader readmethods.VMwareGemFire®automaticallyprovides IPdxReader tothe FromData functionfor IPdxSerializable objects.Usethesamenamesasyoudidin ToData andcallthereadoperationsinthesameorderasyoucalledthewriteoperationsinyour ToData implementation.Example:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.49 10.1
publicvoidFromData(IPdxReaderreader){m_id=reader.ReadInt("id");
boolisIdentity=reader.IsIdentityField("id");
if(isIdentity==false)thrownewIllegalStateException("Portfolioidisidentityfield");
boolisId=reader.HasField("id");
if(isId==false)thrownewIllegalStateException("Portfolioidfieldnotfound");
boolisNotId=reader.HasField("ID");
if(isNotId==true)thrownewIllegalStateException("PortfolioisNotIdfieldfound");
m_pkid=reader.ReadString("pkid");m_position1=(PositionPdx)reader.ReadObject("position1");m_position2=(PositionPdx)reader.ReadObject("position2");m_positions=(Hashtable)reader.ReadObject("positions");m_type=reader.ReadString("type");m_status=reader.ReadString("status");m_names=reader.ReadStringArray("names");m_newVal=reader.ReadByteArray("newVal");m_creationDate=reader.ReadDate("creationDate");m_arrayNull=reader.ReadByteArray("arrayNull");m_arrayZeroSize=reader.ReadByteArray("arrayZeroSize");}
5. Optionally,programyourdomainobject’s equals and hashcode methods.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.50 10.1
IPdxSerializableExampleThenativeclientreleasecontainanexampleshowinghowaclientapplicationcanregisterforserializationofdomainobjectsusingthe.NETIPdxSerializableinterface.
Theexampleislocatedin examples\dotnet\pdxserializable .
Theexampledefinestheserializableclass, Orders ,includingitsserializationanddeserializationmethodsanditsfactorymethod.Oncethesepiecesareinplace,executionissimple:themainroutineoftheexampleregisterstheserializableclassthenperformssomeputandgetoperations.
ExecutionTheexampleperformsasequenceofoperations,displayingsimplelogentriesastheyrun.
Toruntheexample,followtheinstructionsintheREADME.mdfileintheexampledirectory.
Reviewthesourcecodeintheexampledirectorytoseeexactlyhowitoperates.
Beginbyrunningascriptthatsetsuptheserver-sideenvironmentbyinvoking gfsh commandstocreatearegion,alocator,andaserver.
Runtheexampleclientapplication,whichperformsthefollowingsteps:
ConnectstotheserverRegistersthePdxSerializableclassCreatesordersStoresordersRetrievesorders
.NETExampleThissectioncontainscodesnippetsshowinghighlightsofthe.NETPdxSerializableexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.
The.NETexampledefinesaPdxSerializableclasscalled Order thatinheritsfromthe IPdxSerializableinterface.An Order objectcontainsthreefields:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.51 10.1
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();}
The.NETexamplemainlinecreatesacache,thenusesittoregisterthePdxSerializableclassthatwascreatedinOrders.cs:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.52 10.1
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();
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.53 10.1
RemoteQueriesInthistopic
RemoteQueryBasicsQuerylanguage:OQL
CreatingIndexes
RemoteQueryAPIQuery
ExecutingaQueryfromtheClient
.NETQueryExample
UsetheremotequeryAPItoqueryyourcacheddatastoredonacacheserver.
RemoteQueryBasicsQueriesareevaluatedandexecutedonthecacheserver,andtheresultsarereturnedtotheclient.Youcanoptimizeyourqueriesbydefiningindexesonthecacheserver.
Queryingandindexingoperateonlyonremotecacheservercontents.
Querylanguage:OQL
VMwareGemFire®providesaSQL-likequeryinglanguagecalledOQLthatallowsyoutoaccessdatastoredinVMwareGemFire®regions.OQLisverysimilartoSQL,butOQLallowsyoutoquerycomplexobjects,objectattributes,andmethods.
Inthecontextofaquery,specifythenameofaregionbyitsfullpath,startingwithaslash( / ).
Thequerylanguagesupportsdrillingdownintonestedobjectstructures.NesteddatacollectionscanbeexplicitlyreferencedintheFROMclauseofaquery.
Aqueryexecutionreturnsitsresultsaseithera ResultSet ora StructSet .
QuerylanguagefeaturesandgrammararedescribedintheVMwareGemFire®manualatQuerying .
CreatingIndexes
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.54 10.1
Indexescanprovidesignificantperformancegainsforqueryexecution.Youcreateandmaintainindexesonthecacheserver.Fordetailedinformationaboutworkingwithindexesconfiguredonacacheserver,seeWorkingwithIndexes intheserver’sdocumentation.
RemoteQueryAPIThissectiongivesageneraloverviewoftheinterfacesandclassesthatareprovidedbythequerypackageAPI.
Query
Youmustcreatea Query objectforeachnewquery.The Query interfaceprovidesmethodsformanagingthecompilationandexecutionofqueries,andforretrievinganexistingquerystring.
A Query isobtainedfroma QueryService ,whichisobtainedfromoneoftwosources:
Tocreatea Query thatoperatesontheVMwareGemFire®server,useApache::Geode::Client::Pool::GetQueryService() toinstantiatea QueryService obtainedfroma Pool .
Tocreatea Query thatoperatesonyourapplication’slocalcache,useApache::Geode::Client::Cache::GetQueryService() toinstantiatea QueryService obtainedfroma Cache .
ExecutingaQueryfromtheClient
Theessentialstepstocreateandexecuteaqueryare:
1. Createaninstanceofthe QueryService class.IfyouareusingthepoolAPI(recommended),youshouldobtainthe QueryService fromthepool.
2. Createa Query instancethatiscompatiblewiththeOQLspecification.
3. Usethe Query.execute() methodtosubmitthequerystringtothecacheserver.Theserverremotelyevaluatesthequerystringandreturnstheresultstotheclient.
4. Iteratethroughthereturnedobjects.
.NETQueryExample
TheseC#codeexcerptsarefromthe examples\dotnet\remotequery exampleincludedinyourclientdistribution.Seetheexampleforfullcontext.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.55 10.1
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());}
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.56 10.1
ContinuousQueriesInthistopic
ContinuousQueryBasics
TypicalContinuousQueryLifecycle
ExecutingaContinuousQueryfromtheClient.NETContinuousQueryExample
TheC++and.NETclientscaninitiatequeriesthatrunontheVMwareGemFire®cacheserverandnotifytheclientwhenthequeryresultshavechanged.Fordetailsontheserver-sidesetupforcontinuousqueries,seeHowContinuousQueryingWorks intheVMwareGemFire®UserGuide.
ContinuousQueryBasicsContinuousqueryingprovidesthefollowingfeatures:
StandardVMwareGemFire®nativeclientquerysyntaxandsemantics.Continuousqueriesareexpressedinthesamelanguageusedforothernativeclientqueries.SeeRemoteQueries.
StandardVMwareGemFire®events-basedmanagementofCQevents.TheeventhandlingusedtoprocessCQeventsisbasedonthestandardVMwareGemFire®eventhandlingframework.
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.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.57 10.1
2. TheclientinitiatestheCQwithanAPIcalltooneofthe CqQueryexecute* methods.Thisputsthequeryintoa RUNNING stateontheclientandontheserver.Theserverremotelyevaluatesthequerystring,andoptionallyreturnstheresultstotheclient. CqQueryexecute* methodsinclude:
CqQuery.Execute()
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(an ICqListener )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:
varqueryService=pool.GetQueryService();
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.58 10.1
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*/
7. Whenfinished,closeupshop.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.59 10.1
query.Execute();...(respondtoeventsastheyarrive)
query.Stop();query.Close();
cache.Close();
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.60 10.1
Security:AuthenticationandEncryptionMostsecurityconfigurationtakesplaceontheVMwareGemFire®server.Theserver’ssecurityframeworkauthenticatesclientsastheyconnecttoacacheserverandauthorizesclientcacheoperationsusingdeveloper-providedimplementationsforauthenticationandauthorization.
Foranexplanationoftheserver-sideimplementationofsecurityfeatures,seeSecurity intheVMwareGemFire®UserGuide.
ANativeClientapplicationmustaddresstwosecurityconcernswhenconnectingtoaVMwareGemFire®server:
AuthenticationTheClientmustsubmititsauthenticationcredentialstotheserverusingthedeveloper-providedauthenticationimplementationexpectedbytheserver.
TLS/SSLClient/ServerCommunicationEncryptionCommunicationbetweenclientandservershouldbeencryptedsoauthenticationcredentialsandothertransmissionscannotbeviewedbythird-parties.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.61 10.1
AuthenticationAclientisauthenticatedwhenitconnectswithvalidcredentialstoaVMwareGemFire®cacheserverthatisconfiguredwiththeclientauthenticationcallback.Fordetailsontheserver’sroleinauthenticationandwhatitexpectsfromtheclient,seeImplementingAuthentication intheVMwareGemFire®UserGuide.
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:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.62 10.1
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;}}
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.63 10.1
TLS/SSLClient-ServerCommunicationEncryptionThissectiondescribeshowtoimplementTLS-basedcommunicationbetweenyourclientsandserversusingtheOpenSSLencryptionutility.WhenconfiguringTLS/SSLsecurityforyourclient,youmayfindithelpfultorefertoTheSSLsectionoftheVMwareGemFire®UserGuide .
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.CreatekeystoresTheVMwareGemFire®serverrequireskeysandkeystoresintheJavaKeyStore(JKS)formatwhilethenativeclientrequiresthemintheclearPEMformat.Thusyouneedtobeabletogenerateprivate/publickeypairsineitherformatandconvertbetweenthetwousingthe keytool utilityandthe opensslcommand.
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 foradescriptionof
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.64 10.1
theseproperties.
StartingandstoppingtheclientandserverwithSSLinplace
Beforeyoustartandstoptheclientandserver,makesureyouconfigurethenativeclientwiththeSSLpropertiesasdescribedandwiththeserversorlocatorsspecifiedasusual.
Specifically,ensurethat:
TheOpenSSLandVMwareGemFire®DLLsareintherightenvironmentvariablesforyoursystem:PATH forWindows,and LD_LIBRARY_PATH forUnix.
Youhavegeneratedthekeysandkeystores.
Youhavesetthesystemproperties.
FordetailsonstoppingandstartinglocatorsandcacheserverswithSSL,seeStartingUpandShuttingDownYourSystem .
TheVMwareGemFire®Native’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:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.65 10.1
gfsh>startserver--name=my_server--locators=hostname[12345]\--cache-xml-file=server.xml--log-level=fine\--security-properties-file=/path/to/your/geode.properties
Exampleserverstopcommand
gfsh>stopserver--name=my_server
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.66 10.1
FunctionExecutionInthistopic
Server-sideRequirements
Client-sideRequirements
HowFunctionsExecute
ProcessingFunctionResults
FunctionExecutionExample.NETExample
Aclientcaninvokeaserver-residentfunction,withparameters,andcancollectandoperateonthereturnedresults.
Server-sideRequirementsTobecallablefromyourclient,afunctionmustbe
residentontheserver,and
registeredasavailableforclientaccess.
SeeExecutingaFunctioninVMwareGemFire® intheVMwareGemFire®UserGuidefordetailsonhowtowriteandregisterserver-residentfunctions.
Client-sideRequirementsTheclientmustconnecttotheserverthroughaconnectionpoolinordertoinvokeaserver-sidefunction.
HowFunctionsExecute1. Thecallingclientapplicationrunsthe execute methodonthe Execution object.Thefunction
mustalreadyberegisteredontheservers.
2. Thefunctionisinvokedontheserverswhereitneedstorun.TheserversaredeterminedbytheFunctionService on* methodcalls,regionconfiguration,andanyfilters.
3. Ifthefunctionhasresults,theresultisreturnedina ResultCollector object.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.67 10.1
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:onehandlesdataandinformationfromVMwareGemFire®andpopulatestheresultsset,whiletheotherreturnsthecompiledresultstothecallingapplication:
addResult iscalledwhenresultsarrivefromthe Function methods.Use addResult toaddasingleresulttotheResultCollector.endResults iscalledtosignaltheendofallresultsfromthefunctionexecution.getResult isavailabletoyourexecutingapplication(theonethatcallsExecution.execute )toretrievetheresults.Thismayblockuntilallresultsareavailable.clearResults iscalledtoclearpartialresultsfromtheresultscollector.Thisisusedonlyfor
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.68 10.1
highlyavailable onRegion functionswherethecallingapplicationwaitsfortheresults.Ifthecallfails,beforeVMwareGemFire®retriestheexecution,itcalls clearResults toreadytheinstanceforacleansetofresults.
2. Usethe Execution objectinyourexecutingmembertocall withCollector ,passingyourcustomcollector.
FunctionExecutionExampleThenativeclientreleasecontainsanexampleoffunctionexecutionin ../examples/dotnet/functionexecution .
Theexamplebeginswithaserver-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.
.NETExample
Thissectioncontainscodesnippetsshowinghighlightsofthe.NETfunctionexecutionexample.Theyarenotintendedforcut-and-pasteexecution.Forthecompletesource,seetheexamplesourcedirectory.
The.NETexamplecreatesacache,thenusesittocreateaconnectionpool.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.69 10.1
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.
ArrayListkeyArgs=newArrayList();keyArgs.Add(rtimmonsKey);keyArgs.Add(scharlesKey);
Theclientcreatesanexecutionobjectusing Client.FunctionService.OnRegion andspecifyingtheregion.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.70 10.1
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());}}
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.71 10.1
TransactionsInthistopic
NativeClientTransactionAPIs
RunningNativeClientTransactions
ClientTransactionExamples.NETExample
TheNativeClientAPIrunstransactionsontheserverasiftheywerelocaltotheclientapplication.Thus,thekeytorunningclienttransactionsliesinmakingsuretheserverisproperlyconfiguredandprogrammed.ForcompleteinformationabouthowtransactionsareconductedontheVMwareGemFire®server,seetheTransactionssectionoftheVMwareGemFire®UserGuide .
NativeClientTransactionAPIsTheAPIfordistributedtransactionshasthefamiliarrelationaldatabasemethods, begin , commit ,androllback .TherearealsoAPIsavailabletosuspendandresumetransactions.
The.NETclassesforexecutingtransactionsare:
Apache.Geode.Client.CacheTransactionManager
Apache.Geode.Client.TransactionId
RunningNativeClientTransactionsThesyntaxforwritingclienttransactionsisthesameaswithserverorpeertransactions,butwhenaclientperformsatransaction,thetransactionisdelegatedtoaserverthatbrokersthetransaction.
Starteachtransactionwitha begin operation,andendthetransactionwitha commit ora rollback .
Tomaintaincacheconsistency,thelocalclientcacheisnotusedduringatransaction.Whenthetransactioncompletesorissuspended,localcacheusageisreinstated.
Ifthetransactionrunsonserverregionsthatareamixofpartitionedandreplicatedregions,performthefirsttransactionoperationonapartitionedregion.Thissetstheserverdatahostfortheentiretransaction.IfyouareusingPRsingle-hop,single-hopwillbeappliedasusualtothisfirstoperation.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.72 10.1
Inadditiontothefailureconditionscommontoalltransactions,clienttransactionscanalsofailifthetransactiondelegatefails.Ifthedelegateperformingthetransactionfails,thetransactioncodethrowsaTransactionException .
ClientTransactionExamplesThenativeclientreleasecontainsatransactionexamplein ../examples/dotnet/transaction .
Theexampleperformsasequenceofoperations,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.
The.NETexamplecreatesacache,thenusesittocreateaconnectionpool.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.73 10.1
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);}}
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.74 10.1
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.75 10.1
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
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.76 10.1
<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`
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.77 10.1
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;}}
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.78 10.1
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.79 10.1
SystemPropertiesAvarietyofsystempropertiescanbespecifiedwhenaclientconnectstoadistributedsystem,eitherprogrammaticallyorina geode.properties file.See Apache::Geode::Client::SystemProperties inthe.NETAPIdocs.
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,memoryusageisgovernedbyeachregion’sLRUentrieslimit,ifany.
0
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.80 10.1
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
LoggingProperties
log-
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.81 10.1
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
archive-disk- Maximumamountofdiskspace,ingigabytes,allowedforallarchive
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.82 10.1
space-limit
files,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.
SystemPropertiesforClientAuthenticationandAuthorization
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.83 10.1
security-client-auth-factory
Setsthekeyforthe AuthInitialize factoryfunction. empty
security-client-auth-library
Registersthepathtothe securityImpl.dll library. empty
security-client-dhalgo
Diffie-Hellmanbasedcredentialsencryptionisnotsupported. 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
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.84 10.1
ClientCacheXMLReferenceThissectiondocumentstheXMLelementsyoucanusetoconfigureyourVMwareGemFire®nativeclientapplication.
TodefineaconfigurationusingXML:
1. SetcacheconfigurationparametersinadeclarativeXMLfile.Byconvention,thisuserguidereferstothefileas cache.xml ,butyoucanchooseanyname.
2. SpecifythefilenameandpathtoyourXMLconfigurationfilebysettingthe cache-xml-file propertyinthe geode.properties file.Ifyoudonotspecifypath,theapplicationwillsearchforthefileinitsruntimestartupdirectory.
Forexample:
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:XMLEssentials
ThissectionassumesyouarefamiliarwithXML.Whencreatingacacheinitializationfileforyournativeclientapplication,keepthesebasicsinmind:
PlaceanXMLprologatthetopofthefile.Forexample:
<?xmlversion="1.0"encoding="UTF-8"?>
Quoteallparametervalues,includingnumbersandbooleans.Forexample:
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.85 10.1
concurrency-level="10"caching-enabled="true"
SometypesarespecifictotheVMwareGemFire®cacheinitializationfile:
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:
<expiration-attributestimeout="20s"action="destroy"/><expiration-attributestimeout="10s"action="invalidate"/>
Library:Complextypeconsistingofalibrarynameandafunctionname.Usedbytheclienttoinvokefunctions.Forexample:
<persistence-managerlibrary-name="SqLiteImpl"library-function-name="createSqLiteInstance">
CacheInitializationFileElementDescriptions
Thissectionshowsthehierarchyof <client-cache> sub-elementsthatyouusetoconfigureVMwareGemFire®cachesandclients.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>
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.86 10.1
<cache-loader> <cache-listener> <cache-writer> <persistence-manager> <pdx>
Inthedescriptions,elementsandattributesnotdesignated“required”areoptional.
<client-cache>ElementThe<client-cache>elementisthetop-levelelementoftheXSDfile.
Yourdeclarativecachefilemustincludeaschemaofthefollowingform:
<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
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.87 10.1
<pool>ElementThe<pool>elementisacollectionoftheconnectionsbywhichyourclientapplicationcommunicateswiththeVMwareGemFire®server.
Aconnectioncanspecifyeitheralocatororaserver.
A <pool> mustcontainatleastoneconnection,locatororserver,andcancontainmultiplesofeitherorboth.
Sub-elementsof<pool>
A <pool> mustcontainatleastonesub-elementthatspecifiesaconnection,whichcanbeeitheraserveroralocator.Multiplesofeitherorbothtypesarepermitted.
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
Integer>=-1.Themaximumnumberofconnectionstobecreated.Ifall
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.88 10.1
max-connections
oftheconnectionsareinuse,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.
""
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
Boolean.Setsthethreadlocalconnectionspolicyforthispool.Whentrue thenanytimeathreadgoestouseaconnectionfromthispoolit
Attribute Description Default
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.89 10.1
thread-local-connections
willcheckathreadlocalcacheandseeifitalreadyhasaconnectioninit.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><locator> isasub-elementof <pool> thatdefinesaconnectiontoaVMwareGemFire®locator,specifiedbyahostandportcombination.
Attributesof<locator>
Attribute Description
host String.Locatorhostname.
port Integerintherange0-65535,inclusive.Locatorportnumber.
Forexample:
<locatorhost="stax01"port="1001"/>
<server><server> isasub-elementof <pool> thatdefinesaconnectiontoaVMwareGemFire®server,specifiedbyahostandportcombination.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.90 10.1
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.
InordertoconnecttoaVMwareGemFire®server,aclientapplicationmustdefineatleastoneregionwhosenamecorrespondstothatofaregionontheserver.
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.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.91 10.1
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
<cache-listener> library 0 1
<cache-writer> library 0 1
<persistence-manager> listofproperties 0 1
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- String.Setstheinitialentrycapacityfortheregion. 10000
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.92 10.1
capacity
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.
Attribute Description Default
<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
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.93 10.1
<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
<entry-idle-time><entry-idle-time>specifieshowlongthisentryremainsinthecacheafterthelastaccess,andtheexpirationactiontoinvokewhentimerunsout.Thecounterisresetafteranyaccess,includingcreate,put,andgetoperations.
Usethe <expiration-attributes> sub-elementtospecifydurationandexpirationaction.Theattributesof
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.94 10.1
<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.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.95 10.1
<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.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.96 10.1
Attributesof<pdx>
Attribute Description
ignore-unread-fields
Boolean.When true ,donotpreserveunreadPDXfieldsduringdeserialization.Youcanusethisoptiontosavememory.Setthisattributeto true onlyinmembersthatareonlyreadingdatafromthecache.
read-serialized
Boolean.When true ,PDXdeserializationproducesa PdxInstance insteadofaninstanceofthedomainclass.
©Copyright2020VMwareInc.oritsaffiliates.AllRightsReserved.97 10.1
top related