Hello Oracle Coherence

We can run Coherence just as we extract it from its distribution package, relying on its default configuration, but it is usually a smarter idea to provide at least some minimal custom setup for our instance.

We could pass parameters from the command line, or provide XML files with a format and name as expected by coherence.

Here is my tangosol-coherence-override.xml that I used to configure both my coherence server and client applications:
<?xml version='1.0'?>

<coherence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.oracle.com/coherence/coherence-operational-config"
    xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-operational-
config coherence-operational-config.xsd">
    <cluster-config>
        <member-identity>
            <cluster-name>myc</cluster-name>
        </member-identity>

        <multicast-listener>
            <address>224.3.6.0</address>
            <port>9485</port>
            <time-to-live>0</time-to-live>
        </multicast-listener>
    </cluster-config>
</coherence>
All the specified fields should be immediate, maybe with the exception of time-to-live, that is the default surviving time for an object in the cache. As you could expect, zero does not mean "immediate death", but quite the opposite.

Using those configuration, we could finally start writing some Java code. You see that the resulting code is very clean and easy. From the programmer point of you, the cache is nothing more than a Map:
// ...
import com.tangosol.net.*;

// ...

    // setup
    CacheFactory.ensureCluster();
    NamedCache cache = CacheFactory.getCache("hello-example"); // 1

    // input
    String key = "k1";
    String input = "Hello World!";

    // put an item in the cache
    cache.put(key, input); // 2

    // get an item from the cache 
    String output = (String)cache.get(key); // 3
    if(output.compareTo(input) == 0)
        System.out.println("OK");

    // removing an item from the cache
    cache.remove(key);

    // terminate
    CacheFactory.shutdown();
    
// ...
1. There could be many different caches in out Coherence instance, we get the cache that the client want through a dedicated factory.
2. Just like a standard Map, we simply put key and value, and let Coherence to take care of the details. With a variant, we can pass a third parameter, the time to live in the cache for this element, in milliseconds.
3. As the standard Map, we should downcast to the actual type - beware of exceptions! And, if the key is not found, the result would be a null. I didn't check nor for unexpected type nor for null, real code should be more careful.

No comments:

Post a Comment