Blog

How to Place and Retrieve Objects From the Server-Side Cache

by on September 1, 2019

Backendless provides a very powerful and easy-to-use API to work with your server-side cache. The API is multi-platform, which means clients written in different languages can exchange data using the centralized server-side cache storage. The caching API can accept any arbitrary object, a primitive value, or an array of objects/primitive values. Additionally, the caching system can be strongly typed – a client app can specify the type that should be used to deserialize the object.

The example below places an arbitrary object into cache. The object is mapped to a name which identifies it in the context of the application. Then the object is retrieved using the same name:

    Asynchronous sample (Android and Plain Java):

    private static void addToCacheAsync()
    {
        Person p = new Person();
        p.name = "James Bond";
        p.age = 42;
        Backendless.Cache.put( "myobject", p, new AsyncCallback<Object>()
        {
            @Override
            public void handleResponse( Object o )
            {
                System.out.println( "Object has been placed into cache" );
            }
            @Override
            public void handleFault( BackendlessFault backendlessFault )
            {
                System.out.println( "Server reported an error " + backendlessFault.getMessage() );
            }
        } );
    }
    private static void getFromCacheAsync()
    {
        Backendless.Cache.get( "myobject", new AsyncCallback<Person>()
        {
            @Override
            public void handleResponse( Person person )
            {
                System.out.println( "Received object from cache. Person's name - " + person.name + ", age - " + person.age );
            }
            @Override
            public void handleFault( BackendlessFault backendlessFault )
            {
                System.out.println( "Server reported an error " + backendlessFault.getMessage() );
            }
        } );
    }

    Synchronous sample (Plain Java only):

    private static void addToCachetSync()
    {
        Person p = new Person();
        p.name = "James Bond";
        p.age = 42;
        Backendless.Cache.put( "myobject", p );
    }
    public static void getFromCacheSync()
    {
        Person person = Backendless.Cache.get( "myobject", Person.class );
        System.out.println( "Received object from cache. Person's name - " + person.name + ", age - " + person.age );
    }

    - (void)addToCache {
        Person *person = [Person new];
        person.name = @"James Bond";
        person.age = @42;
        [Backendless.shared.cache putWithKey:@"myobject" object:person responseHandler:^{
            NSLog(@"Object has been placed into cache");
        } errorHandler:^(Fault *fault) {
            NSLog(@"Error: %@", fault.message);
        }];
    }
    
    - (void)getFromCache {
        [Backendless.shared.cache getWithKey:@"myobject" responseHandler:^(Person *person) {
            NSLog(@"Received object from cache. Person's name - %@, age - %@", person.name, person.age);
        } errorHandler:^(Fault *fault) {
            NSLog(@"Error: %@", fault.message);
        }];
    }

    func addToCache() {
        let person = Person()
        person.name = "James Bond"
        person.age = 42
        Backendless.shared.cache.put(key: "myobject", object: person, responseHandler: {
            print("Object has been placed into cache")
        }, errorHandler: { fault in
            print("Error: \(fault.message ?? "")")
        })
    }
        
    func getFromCache() {
        Backendless.shared.cache.get(key: "myobject", responseHandler: { person in
            guard let person = person as? Person else { return }
            print("Received object from cache. Person's name - \(person.name ?? ""), age - \(person.age ?? 0)")
        }, errorHandler: { fault in
            print("Error: \(fault.message ?? "")")
        })
    }

    function addToCache() {
      const person = new Person()
      person.name = 'James Bond'
      person.age = 42
    
      Backendless.Cache.put('myobject', person)
        .then(object => {
          console.log('Object has been placed into cache')
        })
        .catch(error => {
          console.error(`Server reported an error - ${ error.message }`)
        })
    }
    
    function getFromCache() {
      Backendless.Cache.get('myobject')
        .then(person => console.log(`Received object from cache. Person's name - ${ person.name }, age - ${ person.age }`))
        .catch(error => console.error(`Server reported an error - ${ error.message }`))
    }
    

    The Person class used in the example is a basic POJO. Notice it does not implement the Serializable interface (it could if you needed it to do so), nor does it need to implement any other interface:

      package com.mbaas.sample;
      public class Person
      {
          public String name;
          public int age;
      }

      @interface Person : NSObject
      
      @property (strong, nonatomic) NSString *name;
      @property (strong, nonatomic) NSNumber *age;
      
      @end

      @objcMembers class Person: NSObject {
          var name: String?
          var age: NSNumber?
      }

      class Person {
        constructor(name, age) {
          this.name = name
          this.age = age
        }
      }
      

      The Caching API supports other useful features, like checking if an object exists in cache, or extending an objects life in cache. These and other features are reviewed in other posts of the Recipe blog series.

      You can view the Backendless documentation here to learn more about the Caching API.

      Leave a Reply