运行环境:JDeveloper 11.1.2.2.0 + Coherence3.7.1 + Oracle Database 10g Express Edition 10.2.0.1。
Coherence中的NamedCache Interface扩展了Map Interface,并提供了很多增值功能:locking & synchronization,storage integration,queries,events aggregations,transactions。
因为NamedCache 是一个接口,因此Cache的实现可以任意切换,而不用改变使用者的代码。
这就是面向接口编程的好处。
Coherence中的CacheFactory是Cache的工厂类,通过它可以获得Cache实例。
重点步骤说明:
1. 创建Coherence应用
(1)选择Custom Application
(2)查看Project Properties,发现Library and Classpath中已经有了Coherence Library。
这是因为之前我们设置了Default Project Properties。
同样看到Run/Debug/Profile中也有了DefaultCacheServer的Profile。(3)新建一个Profile:NoLocalStorage
因为DefaultCacheServer默认是localstorage=true,但Java程序一般都是作为Client进程,因此单独创建一个 localstorage=fasle的Profile。
其中,在Java Options中增加参数:-Dtangosol.coherence.distributed.localstorage=false -Dtangosol.coherence.log.level=3
2. 创建Java类
(1)MyFirstSample.java,向Cache中Put
package com.oracle.coherence.handson;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;
public class MyFirstSample {
public MyFirstSample() {
}
public static void main(String[] args) {
// ensure we are in a cluser
CacheFactory.ensureCluster();
// create or get a named cache called mycache
NamedCache myCache = CacheFactory.getCache("mycache");
// put key, value pair into the cache.
myCache.put("Name", "Tim Middleton");
System.out.println("Value in cache is " + myCache.get("Name"));
}
}
(2)MyFirstSampleReader.java 从Cache中读
package com.oracle.coherence.handson;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;
public class MyFirstSampleReader {
public MyFirstSampleReader() {
}
public static void main(String[] args) {
// ensure we are in a cluser
CacheFactory.ensureCluster();
// create or get a named cache called mycache
NamedCache myCache = CacheFactory.getCache("mycache");
System.out.println("Value in cache is " + myCache.get("Name"));
}
}
(3)CacheInfo.java,查看本地的节点成员
package com.oracle.coherence.handson;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.Cluster;
import com.tangosol.net.Member;
import com.tangosol.net.NamedCache;
import java.util.Iterator;
public class CacheInfo {
public CacheInfo() {
}
public static void main(String[] args) {
// create or get a named cache called mycache
NamedCache myCache = CacheFactory.getCache("mycache");
// get the information about the cluster and local member
Cluster cluster = CacheFactory.getCluster();
Member memberThis = cluster.getLocalMember();
System.out.println("Local member info: " + memberThis);
// list all the members - highlighting the curret one
for (Iterator iter = cluster.getMemberSet().iterator(); iter.hasNext(); ) {
Member member = (Member)iter.next();
System.out.println(member + (member.equals(memberThis) ? " <-- this node" : ""));
}
}
}
3. 运行
(1)选择运行DefaultCacheServer Profile,作为存储数据的Cache。
(2)选择NoLocalStorage Profile,并运行MyFirstSample。
(3)选择NoLocalStorage Profile,并运行MyFirstSampleReader。
(4)选择NoLocalStorage Profile,并运行CacheInfo。
Project 下载:CoherenceApp(Lab3).7z
没有评论:
发表评论