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:

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

    private fun addToCacheAsync() {
       val p = Person()
       p.name = "James Bond"
       p.age = 42
       Backendless.Cache.put("myobject", p, object : AsyncCallback<Any> {
           override fun handleResponse(o: Any) {
               Log.i(TAG, "Object has been placed into cache")
           }
    
           override fun handleFault(backendlessFault: BackendlessFault) {
               Log.e(TAG, "Server reported an error " + backendlessFault.message)
           }
       })
    }
    
    private fun getFromCacheAsync() {
       Backendless.Cache.get("myobject", object : AsyncCallback<Person> {
           override fun handleResponse(person: Person) {
               Log.i(TAG, "Received object from cache. Person's name - " + person.name + ", age - " + person.age)
           }
    
           override fun handleFault(backendlessFault: BackendlessFault) {
               Log.e(TAG, "Server reported an error " + backendlessFault.message)
           }
       })
    }
    

    - (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 }`))
    }
    

    void addToCache() {
     Person p = Person()
       ..name = "James Bond"
       ..age = 42;
     Backendless.cache.put("myobject", p).then((response) {
       print("Object has been placed into cache");
     });
    }
    
    void getFromCache() {
     Backendless.cache.get("myobject").then((person) {
       print("Received object from cache. Person's name - ${person.name}, age - ${person.age}");
     });
    }
    

    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;
      }

      package com.mbaas.sample
      
      class Person {
         var name: String? = null
         var age: Int = 0
      }
      

      @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
        }
      }
      

      import 'package:backendless_sdk/backendless_sdk.dart';
      
      @reflector
      class Person {
       String name;
       int 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