`
longgangbai
  • 浏览: 7337973 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

简单的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

分享到:
评论
2 楼 longgangbai 2013-06-18  
ZT_LY 写道

您好,

    coherence的jvm参数配置:
    -Dtangosol.coherence.cacheconfig=D:/jee-workspace/CoherenceApp/resources/cache-db-config.xml 

   
     这个不是很明白,麻烦问一下该配置的什么地方?
     刚学coherence,不是很明白,coherence版本是 3.7.1。

配置在main类Run的Run Configuration 的Arguments中,运行参数中。
1 楼 ZT_LY 2013-01-16  

您好,

    coherence的jvm参数配置:
    -Dtangosol.coherence.cacheconfig=D:/jee-workspace/CoherenceApp/resources/cache-db-config.xml 

   
     这个不是很明白,麻烦问一下该配置的什么地方?
     刚学coherence,不是很明白,coherence版本是 3.7.1。

相关推荐

    Coherence企业级缓存(五)与Hibernate集成(2) .pdf

    根据提供的文档信息,本文将详细解析Coherence企业级缓存与Hibernate集成的相关知识点,包括配置方法、集成步骤以及实现机制。 ### Coherence企业级缓存简介 Coherence是一款由Oracle公司开发的企业级分布式内存...

    Oracle Coherence中文开发文档

    - **数据库高速缓存**:提高数据库读写性能。 - **HTTP会话管理**:管理Web应用的用户会话数据。 - **网格代理调用**:允许不同节点之间的远程方法调用。 - **分布式查询**:支持在分布式的环境中执行查询操作。 ##...

    Oracle Toplink Grid

    这篇文章主要关注如何使用Coherence作为TopLink的二级(L2)缓存,以优化JPA(Java Persistence API)实体的读写操作。 首先,软件需求包括Oracle TopLink 11g版本11.1.1.0.0,该版本集成了EclipseLink,以及...

    分布式缓存与JavaEE

    随着大数据时代的到来,NoSQL数据库因其高并发读写能力和海量存储能力而被广泛应用。例如: - **Google File System (GFS)**:用于存储大规模数据。 - **BigTable**:用于处理大规模结构化数据。 - **Hadoop**:...

    毕业设计进展汇报ppt

    7. 缓存框架的测试结果:测试了写入内存、写入硬盘、XML文件等缓存方法,并实现了缓存数据的读写操作。 8. 缓存框架的主要类文件:Text、Cache、MemoryStore、DiskStore、CacheConfiguration、Element等。 9. 缓存...

    j2ee cache framework

    Java的`synchronized`关键字、`java.util.concurrent`包下的工具类,以及各种锁策略(如读写锁、乐观锁、悲观锁等)都可以用于实现缓存的并发安全。 ### 六、缓存的更新与失效 1. **缓存穿透**:当缓存和数据库均...

    深入解读:从设计出发优化系统性能

    - 采用缓存技术(如Coherence):缓存经常访问的数据可以有效减轻数据库的压力,提高系统响应速度。 #### 四、案例分析与实践 - **业务需求分析**:首先明确业务需求,例如新契约的处理、保费计算、保单打印等,...

    The art of multiprocessor programming

    但是,这同时也引入了并行计算中的一些固有难题,比如竞争条件(race condition)、死锁(deadlock)、饥饿(starvation)以及缓存一致性(cache coherence)等问题。 书中主要内容涵盖了并行编程的基本原理和技术...

    Programming-Persistent-Memory-2020.pdf

    1. 内存映射文件(Memory-Mapped Files):这是将文件内容映射到内存地址空间的技术,让应用程序可以直接对内存中的数据进行读写,从而实现高速访问。 2. 存储持久性(Memory Persistence):由于持久性内存保留...

    weblogic性能调优

    - **TimesTen**:针对物理内存特别优化的数据库,能够提供非常高的读写性能,适用于交易处理和查询密集型应用。 - **RAC**(Real Application Clusters):通过集群技术提高数据库层的可用性和可扩展性。 #### 三、...

Global site tag (gtag.js) - Google Analytics