DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • DevSecOps: Enhancing Security With Vulnerability Scanning of Images and Source Code in CI/CD
  • What Is API-First?
  • Introduction to Couchbase for Oracle Developers and Experts: Part 2 - Database Objects

Trending

  • DevOps Is Dead, Long Live Platform Engineering
  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Why We Chose Iceberg Over Delta After Evaluating Both at Scale
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  1. DZone
  2. Data Engineering
  3. Data
  4. Working With JSON Document in Gemfire Cache

Working With JSON Document in Gemfire Cache

A quick tutorial, with code, describing how to store a JSON document in a Gemfire cache, from the very first step of setting up the environment.

By 
Diraj Pandey user avatar
Diraj Pandey
·
Feb. 22, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
4.6K Views

Join the DZone community and get the full member experience.

Join For Free

JSON Document Store in Gemfire Cache.

Let us consider below JSON needs to stored in Gemfire Cache.

Java
 




x


 
1
{
2
          "firstName" : "Smith",
3
          "lastName" : "Dagg",
4
          "age" : 31,
5
          "address" : {
6
            "streetAddress" : "1930 Apple Dr",
7
            "city" : "Wilmington",
8
            "state" : "DE",
9
            "postalCode" : "12345"
10
          },
11
          "phoneNumber" : [ {
12
            "type" : "mobile",
13
            "number" : "123 456 1234"
14
          }
15
        ]
16
       }



Let us set up the environment; it involves Server and Client setup.

The server configuration looks like below.

cache_server.xml

Java
xxxxxxxxxx
1
23
 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<cache
3
    xmlns="http://geode.apache.org/schema/cache"
4
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
    xsi:schemaLocation="http://geode.apache.org/schema/cache
6
    http://geode.apache.org/schema/cache/cache-1.0.xsd"
7
    version="1.0">
8
    <cache-server port="40404"></cache>
9
    <region name="jsonPersonRegion">
10
       <region-attributes refid="REPLICATE" ></region>
11
    </region>
12
</cache>


The cache server configures a cache to serve caching clients. The Region 'jsonPersonRegion' also is configured with a loader.

Above Cache has been configured with port 40404, region name is 'jsonPersonRegion' and region is REPLICATED type. If data is in sync with all the nodes then it is REPLICATED.

Below is how the client is setup:

client.xml

Java
 




xxxxxxxxxx
1
23


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<client-cache
3
    xmlns="http://geode.apache.org/schema/cache"
4
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
    xsi:schemaLocation="http://geode.apache.org/schema/cache
6
    http://geode.apache.org/schema/cache/cache-1.0.xsd"
7
    version="1.0">
8
    <pool name="serverPool">
9
        <locator host="hostA" port="40404"/>
10
    </pool>
11
    <region name=" jsonPersonRegion" refid="REPLICATE"/>
12
</client-cache>



Client cache configures a region as a client region in a client/server cache. The region's pool connects to the cache server.

 Below is the cache client code which stores the above json document and does query on the region.

JSONGemFireClient.java

Java
 




xxxxxxxxxx
1
43


 
1
import java.util.List;
2
import org.json.simple.JSONObject; 
3
import com.gemstone.gemfire.cache.Region;
4
import com.gemstone.gemfire.cache.client.ClientCache;
5
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
6
import com.gemstone.gemfire.cache.query.SelectResults;
7
import com.gemstone.gemfire.pdx.JSONFormatter;
8
import com.gemstone.gemfire.pdx.PdxInstance;
9
10
public class JSONGemFireClient 
11
{
12
   public static final String REGION_PERSON = " jsonPersonRegion";
13
   public ClientCache cache = null;
14
   personJson ="{\"firstName\":\"Smith\",\"lastName\":\"Dagg\",\"age\":31,\"address\":{\"streetAddress\":\"1930 Apple Dr\",\"city\":\"Wilmington\",\"state\":\"DE\",\"postalCode\":\"12345\"},\"phoneNumber\":[{\"type\":\"mobile\",\"number\":\"123 456 1234\"}]}"
15
16
   public JSONGemFireClient()
17
   {
18
    cache = new ClientCacheFactory()
19
          .set("name", "JSONClient")
20
          .set("cache-xml-file", "xml/client.xml")
21
          .create();   
22
   }
23
24
@SuppressWarnings("unchecked")
25
   public void run() throws Exception
26
   {
27
    JSONObject obj = null;
28
    Log.info("Connecting to the distributed system and creating the cache.");
29
     
30
    // Get the region
31
    Region<String, PdxInstance> personregion =cache.getRegion(REGION_PERSON);
32
    Log.info("Example region \"" + personregion.getFullPath() + "\" created is cache.");
33
     //Store string key, value pair in region
34
    personregion.put(“person1”,JSONFormatter.fromJSON(personString.toJSONString();
35
36
    // Query person region
37
    PdxInstance personinfo = personregion.get(“person1”);
38
    log.info(JSONFormatter.toJSON(personinfo));
39
    personFirstName = personinfo.getValue(“firstName”);
40
    log.info(“First Name is “, personFirstName);
41
    cache.close();
42
    }
43
}



The JSONFormatter API allows you to put JSON formatted documents into regions and retrieve them later by storing the documents internally as PdxInstances.

You can then use the JSONFormatter to convert the PdxInstance results back into the JSON document.

fromJSON: 

Creates a PdxInstance from a JSON byte array. Returns the PdxInstance

Creates a PdxInstance from a JSON string. Returns the PdxInstance.

toJSON

Reads a PdxInstance and returns a JSON string.

toJSONByteArray

Reads a PdxInstance and returns a JSON byte array. 

JSON Cache (computing) Document

Opinions expressed by DZone contributors are their own.

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • DevSecOps: Enhancing Security With Vulnerability Scanning of Images and Source Code in CI/CD
  • What Is API-First?
  • Introduction to Couchbase for Oracle Developers and Experts: Part 2 - Database Objects

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook