Use the Java API for Caching
The Java API for caching enables your Java application to write values to, read values from, delete values in, and clear the cache. This API is an open source framework with sources hosted on GitHub and binaries both directly downloadable from and available through Maven Central.
This section describes the conceptual framework and basic steps for how to use the Java API for caching. You can download the Java classes and read the Javadoc pages at Oracle Application Container Cloud Service Java SDK for Caching. Tutorials that use this API are Creating an Application Using the Java API for Caching on Oracle Application Container Cloud Service and Creating an Application Using the Java API for Caching and a Database on Oracle Application Container Cloud Service.
To access a cache, your application must first define a SessionProvider
and a Session
object:
-
Create a
SessionProvider
obejct for a cache service that you previously created. Provide a URL with the cache service name and the port that supports the desired transport protocol:1444
for GRPC or8080
for REST. When using REST, the hostname is followed by/ccs
. A GRPC example:SessionProvider sp = new RemoteSessionProvider("http://MyCache:1444");
A REST example:
SessionProvider sp = new RemoteSessionProvider("http://MyCache/ccs:8080");
-
Obtain a
Session
object from theSessionProvider
object using a specific transport. A GRPC example:Session cs = sp.createSession(Transport.grpc());
A REST example:
Session cs = sp.createSession(Transport.rest());
-
Obtain a
Cache
object from theSession
object. The cache in this example is namedusers
, and it stores objects of classUser
.Cache<Users> users = cs.getCache("users");
After your application has obtained a Cache
object, it can interact with the cache. The API includes the methods Cache.get()
, Cache.put()
, Cache.replace()
, and Cache.remove()
. For example, the code to put a User
object into the users
cache with the user’s ID as the key is as follows:
users.put(user.getId(),user);
Removing an object from a cache can be as simple as calling users.remove(id)
, but because caches are not local, the remove operation provides optimization options. The Cache.remove()
method lets you specify, among other things, whether you want the removed object returned. By default it returns null
. To return the removed object, use the Return.OLD_VALUE
option. For example:
User user = users.remove(id, Return.OLD_VALUE);
Like Cache.remove()
, the Cache.replace()
method provides optimization options and returns null
by default. For example:
users.replace(id, user);
For full details about these methods, see the Javadoc pages.