简单的Coherence 实现数据库读写缓存

               自定义数据缓存DAO类,必须实现com.tangosol.net.cache.CacheStore接口或者
com.tangosol.net.cache.CacheLoader 接口,由于 com.tangosol.net.cache.AbstractCacheStore 继承了com.tangosol.net.cache.AbstractCacheLoader 实现了   com.tangosol.net.cache.CacheStore类。

实现类如下:

package com.etrip.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.tangosol.net.cache.AbstractCacheStore;
/**
 * 自定义数据缓存DAO类,必须实现com.tangosol.net.cache.CacheStore接口或者
 * com.tangosol.net.cache.CacheLoader 接口,由于 com.tangosol.net.cache.AbstractCacheStore
 *  继承了com.tangosol.net.cache.AbstractCacheLoader 实现了 
 *  com.tangosol.net.cache.CacheStore类。
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:
 * @Date:2013-1-4
 * @author 
 * @version 1.0
 */
public class DBCacheStore extends AbstractCacheStore {

	public DBCacheStore(String sTableName) {
		m_sTableName = sTableName;
		configureConnection();
	}

	protected void configureConnection() {
		try {
		
			Class.forName(DB_DRIVER);
			m_con = DriverManager.getConnection(DB_URL, DB_USERNAME,
					DB_PASSWORD);
			m_con.setAutoCommit(true);
		} catch (Exception e) {
			throw ensureRuntimeException(e, "Connection failed");
		}
	}

	public String getTableName() {
		return m_sTableName;
	}

	public Connection getConnection() {
		return m_con;
	}

	public Object load(Object oKey) {
		Object oValue = null;
		Connection con = getConnection();
		String sSQL = "SELECT id, value FROM " + getTableName()
				+ " WHERE id = ?";
		try {
			PreparedStatement stmt = con.prepareStatement(sSQL);

			stmt.setString(1, String.valueOf(oKey));

			ResultSet rslt = stmt.executeQuery();
			if (rslt.next()) {
				oValue = rslt.getString(2);
				if (rslt.next()) {
					throw new SQLException("Not a unique key: " + oKey);
				}
			}
			stmt.close();
		} catch (SQLException e) {
			throw ensureRuntimeException(e, "Load failed: key=" + oKey);
		}
		return oValue;
	}

	public void store(Object oKey, Object oValue) {
		Connection con = getConnection();
		String sTable = getTableName();
		String sSQL;

		if (load(oKey) != null) {

			sSQL = "UPDATE " + sTable + " SET value = ? where id = ?";
		} else {

			sSQL = "INSERT INTO " + sTable + " (value, id) VALUES (?,?)";
		}
		try {
			PreparedStatement stmt = con.prepareStatement(sSQL);
			int i = 0;
			stmt.setString(++i, String.valueOf(oValue));
			stmt.setString(++i, String.valueOf(oKey));
			stmt.executeUpdate();
			stmt.close();
		} catch (SQLException e) {
			throw ensureRuntimeException(e, "Store failed: key=" + oKey);
		}
	}

	public void erase(Object oKey) {
		Connection con = getConnection();
		String sSQL = "DELETE FROM " + getTableName() + " WHERE id=?";
		try {
			PreparedStatement stmt = con.prepareStatement(sSQL);

			stmt.setString(1, String.valueOf(oKey));
			stmt.executeUpdate();
			stmt.close();
		} catch (SQLException e) {
			throw ensureRuntimeException(e, "Erase failed: key=" + oKey);
		}
	}

	public void eraseAll(Collection colKeys) {
		super.eraseAll(colKeys);
	}

	public Map loadAll(Collection colKeys) {
		return super.loadAll(colKeys);
	}

	public void storeAll(Map mapEntries) {
		super.storeAll(mapEntries);
	}

	public Iterator keys() {
		Connection con = getConnection();
		String sSQL = "SELECT id FROM " + getTableName();
		List list = new LinkedList();

		try {
			PreparedStatement stmt = con.prepareStatement(sSQL);
			ResultSet rslt = stmt.executeQuery();
			while (rslt.next()) {
				Object oKey = rslt.getString(1);
				list.add(oKey);
			}
			stmt.close();
		} catch (SQLException e) {
			throw ensureRuntimeException(e, "Iterator failed");
		}

		return list.iterator();
	}

	protected Connection m_con;
	protected String m_sTableName;
	private static final String DB_DRIVER = "com.mysql.jdbc.Driver";

	private static final String DB_URL = "jdbc:mysql://localhost:3306/biz?user=root&password=123456&useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false";

	private static final String DB_USERNAME = "root";
	private static final String DB_PASSWORD = "123456";

	
}

 

 

coherence的配置文件:

<?xml version="1.0"?>
<cache-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://xmlns.oracle.com/coherence/coherence-cache-config"
              xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-cache-config coherence-cache-config.xsd">
 <caching-scheme-mapping>
  <!-- 
    Caches with names that start with 'DBBacked' will be created 
    as distributed-db-backed.   
    -->
  <cache-mapping>
   <cache-name>DBBacked*</cache-name>
   <scheme-name>distributed-db-backed</scheme-name>
  </cache-mapping>
    <cache-mapping>
       <cache-name>VirtualCache</cache-name>
       <scheme-name>distributed-db-backed</scheme-name>
   </cache-mapping>
 </caching-scheme-mapping>
 <caching-schemes>
  <!-- 
    DB Backed Distributed caching scheme.
    -->
  <distributed-scheme>
   <scheme-name>distributed-db-backed</scheme-name>
   <service-name>DistributedCache</service-name>
   <backing-map-scheme>
    <read-write-backing-map-scheme>
     <internal-cache-scheme>
      <class-scheme>
       <class-name>com.tangosol.util.ObservableHashMap</class-name>
      </class-scheme>
     </internal-cache-scheme>
     <cachestore-scheme>
      <class-scheme>
       <class-name>com.etrip.app.DBCacheStore</class-name>
       <init-params>
        <init-param>
         <param-type>java.lang.String</param-type>
         <param-value>CATALOG</param-value>
        </init-param>
       </init-params>
      </class-scheme>
     </cachestore-scheme>
     <read-only>false</read-only>
     <!--
        To make this a write-through cache just change the value below to 0 (zero)
        -->
     <write-delay-seconds>0</write-delay-seconds>
    </read-write-backing-map-scheme>
   </backing-map-scheme>
<autostart>true</autostart>
</distributed-scheme>
</caching-schemes>
</cache-config>

 

coherence的JVM参数配置如下:

-Dtangosol.coherence.cacheconfig=D:/jee-workspace/CoherenceApp/resources/cache-db-config.xml

 

测试代码:

package com.etrip.app;

import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;
import com.tangosol.net.cache.ContinuousQueryCache;
import com.tangosol.util.Filter;
import com.tangosol.util.extractor.IdentityExtractor;
import com.tangosol.util.filter.LikeFilter;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:
 * @Date:2013-1-5
 * @author 
 * @version 1.0
 */
public class DatabaseCache {
	NamedCache cache;

	public DatabaseCache() {
	}

	public void createCache() {
		cache = CacheFactory.getCache("DBBackedCache");
	}


	public void retrieveEntry() {
		System.out.println((String) cache.get("catalog1"));
	}

	public void eraseEntry() {
		cache.remove(new String("catalog3"));
	}

	public void queryCache() {
		Filter filter = new LikeFilter(IdentityExtractor.INSTANCE, "Tuning%",
				'\\', true);
		HashSet hashSet = new HashSet();
		hashSet.add(new String("catalog1"));
		hashSet.add(new String("catalog2"));
		hashSet.add(new String("catalog3"));

		Map map = cache.getAll(hashSet);
		ContinuousQueryCache queryCache = new ContinuousQueryCache(cache,
				filter);
		Set results = queryCache.entrySet(filter);
		/* Set results = cache.entrySet(filter); */

		if (results.isEmpty())
			System.out.println("Result Set Empty");
		for (Iterator i = results.iterator(); i.hasNext();) {
			Map.Entry e = (Map.Entry) i.next();
			System.out.println("Catalog ID: " + e.getKey() + ", Title: "
					+ e.getValue());
		}
	}

	public static void main(String[] args) {
		DatabaseCache databaseCache = new DatabaseCache();
		//创建相关的缓存
		databaseCache.createCache();
		//查询缓存的数据
		databaseCache.queryCache();
		//获取缓存的对象
		databaseCache.retrieveEntry();
		 
	}
}

 

 

结果:

 

2013-01-05 17:23:59.268/0.362 Oracle Coherence 3.7.1.1 <Info> (thread=main, member=n/a): Loaded operational configuration from "jar:file:/D:/app/Oracle/Middleware/coherence_3.7/lib/coherence.jar!/tangosol-coherence.xml"
2013-01-05 17:23:59.321/0.415 Oracle Coherence 3.7.1.1 <Info> (thread=main, member=n/a): Loaded operational overrides from "jar:file:/D:/app/Oracle/Middleware/coherence_3.7/lib/coherence.jar!/tangosol-coherence-override-dev.xml"
2013-01-05 17:23:59.322/0.416 Oracle Coherence 3.7.1.1 <D5> (thread=main, member=n/a): Optional configuration override "/tangosol-coherence-override.xml" is not specified
2013-01-05 17:23:59.326/0.421 Oracle Coherence 3.7.1.1 <D5> (thread=main, member=n/a): Optional configuration override "/custom-mbeans.xml" is not specified

Oracle Coherence Version 3.7.1.1 Build 28901
 Grid Edition: Development mode
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

2013-01-05 17:23:59.549/0.643 Oracle Coherence GE 3.7.1.1 <Info> (thread=main, member=n/a): Loaded cache configuration from "file:/D:/jee-workspace/CoherenceApp/resources/cache-db-config.xml"
2013-01-05 17:24:00.378/1.472 Oracle Coherence GE 3.7.1.1 <D4> (thread=main, member=n/a): TCMP bound to /172.30.101.179:8088 using SystemSocketProvider
2013-01-05 17:24:03.808/4.902 Oracle Coherence GE 3.7.1.1 <Info> (thread=Cluster, member=n/a): Created a new cluster "cluster:0xFCDB" with Member(Id=1, Timestamp=2013-01-05 17:24:00.531, Address=172.30.101.179:8088, MachineId=6892, Location=site:,machine:longgangbai-PC,process:6844, Role=EtripAppDatabaseCache, Edition=Grid Edition, Mode=Development, CpuCount=4, SocketCount=4) UID=0xAC1E65B30000013C0A0625931AEC1F98
2013-01-05 17:24:03.815/4.909 Oracle Coherence GE 3.7.1.1 <Info> (thread=main, member=n/a): Started cluster Name=cluster:0xFCDB

Group{Address=224.3.7.0, Port=37000, TTL=4}

MasterMemberSet(
  ThisMember=Member(Id=1, Timestamp=2013-01-05 17:24:00.531, Address=172.30.101.179:8088, MachineId=6892, Location=site:,machine:longgangbai-PC,process:6844, Role=EtripAppDatabaseCache)
  OldestMember=Member(Id=1, Timestamp=2013-01-05 17:24:00.531, Address=172.30.101.179:8088, MachineId=6892, Location=site:,machine:longgangbai-PC,process:6844, Role=EtripAppDatabaseCache)
  ActualMemberSet=MemberSet(Size=1
    Member(Id=1, Timestamp=2013-01-05 17:24:00.531, Address=172.30.101.179:8088, MachineId=6892, Location=site:,machine:longgangbai-PC,process:6844, Role=EtripAppDatabaseCache)
    )
  MemberId|ServiceVersion|ServiceJoined|MemberState
    1|3.7.1|2013-01-05 17:24:03.808|JOINED
  RecycleMillis=1200000
  RecycleSet=MemberSet(Size=0
    )
  )

TcpRing{Connections=[]}
IpMonitor{AddressListSize=0}

2013-01-05 17:24:03.861/4.955 Oracle Coherence GE 3.7.1.1 <D5> (thread=Invocation:Management, member=1): Service Management joined the cluster with senior service member 1
2013-01-05 17:24:04.140/5.234 Oracle Coherence GE 3.7.1.1 <D5> (thread=DistributedCache, member=1): Service DistributedCache joined the cluster with senior service member 1
Catalog ID: catalog1, Title: Tuning Undo Tablespace
Catalog ID: catalog2, Title: Tuning Your View Objects
Tuning Undo Tablespace
2013-01-05 17:24:04.611/5.705 Oracle Coherence GE 3.7.1.1 <D4> (thread=ShutdownHook, member=1): ShutdownHook: stopping cluster node
2013-01-05 17:24:04.613/5.707 Oracle Coherence GE 3.7.1.1 <D5> (thread=Cluster, member=n/a): Service Cluster left the cluster
2013-01-05 17:24:04.616/5.710 Oracle Coherence GE 3.7.1.1 <D5> (thread=DistributedCache, member=n/a): Service DistributedCache left the cluster

你可能感兴趣的:(Coherence,CacheStore,CacheLoader)