`

Hibernate和 OsCache的使用

 
阅读更多
下载地址:http://java.net/downloads/oscache/

oscache这个jar里面的jms架包已经无法下载了。
那么我就在网上自己下载了一个jms.jar安装到本地的仓库中去,就ok了。
进入安装maven的目录bin中,执行如下命令:
mvn install:install-file -Dfile=jms-1.1.jar -DgroupId=javax.jms -DartifactId=jms -Dversion=1.1 -Dpackaging=jar
其中最重要的参数是:-Dfile=jar包放的目录
-DgroupId ,-DartifactId ,-Dversion ,-Dpackaging这几个参数.

然后就可以使用:
		<dependency>
			<groupId>javax.jms</groupId>
			<artifactId>jms</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>opensymphony</groupId>
			<artifactId>oscache</artifactId>
			<version>${oscache.version}</version>
		</dependency>


hibernate使用OSCachehttp://www.verydemo.com/demo_c146_i3116.html
拷oscache-2.4.1.jar到WEB-INF/lib下面,添加oscache.properties文件到classes,oscache.properties文件配置可以参考oscache-2.4.1-full.zip包里面的oscache.properties文件.

1、hibernate使用OSCache。

在spring配置文件,session bean的hibernateProperties属性添加:

<prop key="hibernate.current_session_context_class">thread</prop> 
    <prop key="hibernate.cache.use_query_cache">true</prop> 
                <prop key="hibernate.cache.use_second_level_cache">true</prop> 
                <prop key="hibernate.cache.provider_class">com.opensymphony.oscache.hibernate.OSCacheProvider</prop> 
                <prop key="hibernate.jdbc.batch_size">25</prop> 


在*.hbm.xml文件中添加<cache usage="read-only"/>

2、ibatis中使用OSCache

在sql-map-config.xml文件<sqlMapConfig>树下配置
<settings cacheModelsEnabled="true" lazyLoadingEnabled="true" enhancementEnabled="true" errorTracingEnabled="true"/> 


在xml映射文件中添加:

<cacheModel id="userCache" type="OSCACHE"> 
  <!-- 24小时强制清空缓冲区的所有内容 --> 
  <flushInterval hours="24"/> 
  <!-- 指定执行特定的statement时,将缓存清空 --> 
  <flushOnExecute statement="update_user" /> 
   <!-- cache的最大容积 -->  
  <property name="size" value="1000" /> 
</cacheModel>


statement语句中指定要使用的缓存:

<select id="findUserByDept" parameterClass="java.util.HashMap" resultClass="java.util.HashMap" cacheModel="userCache">



OSCache - 在Hibernate中应用
OSCache - 在Hibernate中使用
创建一个Java工程OSCacheTest,在其中引入Hibernate 3.2的类库文件。因为需要使用OSCache,还需要引入oscache-2.1.jar包。
一般使用OSCache缓存需要进行三个步骤的配置,具体如下:
步骤一:在Hibernate中配置OSCache
1. 在Hibernate配置文件中打开二级缓存的配置,如下:
<property name="cache.use_second_level_cache">true</property>
2. 这个值在配置文件中,缺省是打开的。这只是打开二级缓存,并没有指定使用哪个二级缓存。所以需要指定使用的何种二级缓存。配置如下:
<property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>
特别注意:关于二级缓存的配置,必须在<mapping resource="…………" />配置之前,否则报错

步骤二:配置OSCache配置文件
关于缓存中存放多少数据,Hibernate是不关心的,全部由OSCache来完成。需要将OSCache的配置文件oscache.properties放入classpath中(注意不能修改这个文件名),对二级缓存进行具体配置。
在oscache.properties中,有如下的参数配置:cache.capacity=1000
这个数值代表放入缓存的对象数量,这个数量根据用户机器的内存来配置,一般只需要配置这个参数即可。

步骤三:通知Hibernate那些类需要OSCache进行缓存
这个步骤有两种方式可以使用,其作用相同:
第1种:在hibernate.cfg.xml的session-factory中加入:
<class-cache usage="read-only" class="com.mixele.oscache.entity.UserOS"/>

第2种:在映射文件的class元素加入子元素:
<class-cache usage="read-only" />


关于usage属性,有4个值可以配置:
read-only:只读,缓存效率最高,用于不更新的数据
read-write:可读写
nonstrict-read-write:用于不重视并发修改的操作(会出现一定的错误数据,即不同步数据)
transactional:事务缓存,可支持事务回滚(OSCache中没有此项功能)

经过以上配置,OSCache缓存就已经生效。
编写测试程序:
Hibernate配置:
<hibernate-configuration>
    <session-factory>
    	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/cachetest</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">create</property>
		
		<property name="cache.use_second_level_cache">true</property>
		<property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>
		
		<property name="generate_statistics">true</property>
		<mapping resource="com/mixele/oscache/entity/UserOS.hbm.xml" />
    </session-factory>
</hibernate-configuration>




POJO类及hbm:
public class UserOS {
	private int id;
	private String name;
	private Date birthday;
	………………
}


<hibernate-mapping package="com.mixele.oscache.entity">
	<class name="UserOS">
        <cache usage="read-only"/>
		<id name="id"> <generator class="native"/> </id>
		<property name="name" length="100"/>
		<property name="birthday"/>
	</class>
</hibernate-mapping>




缓存测试类:
public class CacheTest{
	public static void main(String [] args) {
		int num = 1;
		DataPutInDB.saveData(num);
		for(int i=0;i<num;i++) {
			getOSCacheCache(i+1);
		}
		Statistics st = HibernateUtil.getSessionfactory().getStatistics();
		System.out.println("输出统计信息............");
		System.out.println(st);
		System.out.println("放入: "+st.getSecondLevelCachePutCount()+"次");
		System.out.println("命中: "+st.getSecondLevelCacheHitCount()+"次");
		System.out.println("失去: "+st.getSecondLevelCacheMissCount()+"次");
	}
	
	static UserOS getOSCacheCache(int id) {
		Session s = null;
		UserOS useros = null;
		try{
			s = HibernateUtil.getSession();
			useros = (UserOS)s.get(UserOS.class, id);//第一次查询,二级缓存中没有信息,miss一次
			useros = (UserOS)s.load(UserOS.class, id);//第二次查询,在一级缓存中找到,不进入二级缓存
			s.clear();//清空一级缓存
		}finally{
			if(s != null){ 
				s.close();
			}
		}
		for(int i=1;i<101;i++){
			try{
				s = HibernateUtil.getSession();
				useros = (UserOS)s.get(UserOS.class, id);//在二级缓存中找到,hit两次
				System.out.println("第"+i+"次从二级缓存查找   "+useros.getClass());
			}finally{
				if(s != null){ s.close(); }
			}
		}
		return useros;
	}
}






OSCache----Hibernate和 OsCache的使用http://blog.csdn.net/joliny/article/details/2090692
OSCache标记库由OpenSymphony设计,它是一种开创性的JSP定制标记应用,提供了在现有
JSP页面之内实现快速内存缓冲的功能。OSCache是个一个广泛采用的高性能的J2EE缓存框架,
OSCache能用于任何Java应用程序的普通的 缓存解决方案。OSCache有以下特点:缓存任何对象,
你可以不受限制的缓存部分jsp页面或HTTP请求,任何java对象都可以缓存。 拥有全面的
API--OSCache API给你全面的程序来控制所有的OSCache特性。 永久缓存--缓存能随意的写入硬盘,
因此允许昂贵的创建(expensive-to-create)数据来保持缓存,甚至能让应用重启。 支持集群--
集群缓存数据能被单个的进行参数配置,不需要修改代码。 缓存记录的过期--你可以有最大限度的
控制缓存对象的过期,包括可插入式的刷新策略(如果默认性能不需要时)。
OSCache是当前运用最广的缓存方案,JBoss,Hibernate,Spring等都对其有支持,
下面简单介绍一下OSCache的配置和使用过程。

1.安装过程
从http://www.opensymphony.com/oscache/download.html下载合适的OSCache版本,
我下载的是oscache-2.0.2-full版本。
解压缩下载的文件到指定目录
从解压缩目录取得oscache.jar 文件放到 /WEB-INF/lib 或相应类库目录 目录中,
jar文件名可能含有版本号和该版本的发布日期信息等,如oscache-2.0.2-22Jan04.jar如果你的jdk版本为1.3.x,
建议在lib中加入Apache Common Lib 的commons-collections.jar包。
如jdk是1.4以上则不必
从src或etc目录取得oscache.properties 文件,放入src根目录或发布环境的/WEB-INF/classes 目录
如你需要建立磁盘缓存,须修改oscache.properties 中的cache.path信息 (去掉前面的#注释)。
win类路径类似为c://app//cache
unix类路径类似为/opt/myapp/cache
拷贝OSCache标签库文件oscache.tld到/WEB-INF/classes目录。

现在你的应用目录类似如下:
$WEB_APPLICATION/WEB-INF/lib/oscache.jar
$WEB_APPLICATION/WEB-INF/classes/oscache.properties
$WEB_APPLICATION/WEB-INF/classes/oscache.tld


将下列代码加入web.xml文件中
<taglib>
<taglib-uri>oscache</taglib-uri>
<taglib-location>/WEB-INF/classes/oscache.tld</taglib-location>
</taglib>


2.为了便于调试日志输出,须加入commons-logging.jar和log4j-1.2.8.jar到当前类库路径中

在src目录加入下面两个日志输出配置文件:
log4j.properties 文件内容为:
log4j.rootLogger=DEBUG,stdout,file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[start]%d{yyyy/MM/dd/ HH:mm:ss}[DATE]%n%p
   [PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=oscache.log
log4j.appender.file.MaxFileSize=100KB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[start]%d{yyyy/MM/dd/ HH:mm:ss}[DATE]%n%p[PRIORITY]
   %n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n
log4j.logger.org.apache.commons=ERROR
log4j.logger.com.opensymphony.oscache.base=INFO
commons-logging.properties 文件内容为
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JCategoryLog



3.hibernate-session配置
 
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingResources">
            <list>
                <value>com/ouou/album/model/Albums.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
                <!--<prop key="hibernate.query.substitutions">true 'Y', false 'N'</prop>-->
                <prop key="hibernate.query.substitutions">true 1, false 0</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>                                              <prop key="hibernate.cache.provider_class">com.opensymphony.oscache.hibernate.OSCacheProvider
                 </prop>
                <prop key="hibernate.show_sql">true</prop>
                <!--<prop key="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop> -->
                <prop key="hibernate.jdbc.batch_size">25</prop>
            </props>
        </property>
    </bean>



4.oscache.properties 文件配置向导
cache.memory
值为true 或 false ,默认为在内存中作缓存,
如设置为false,那cache只能缓存到数据库或硬盘中,那cache还有什么意义:)
cache.persistence.class
持久化缓存类,如此类打开,则必须设置cache.path信息
cache.capacity
缓存元素个数
cache.cluster 相关
为集群设置信息。

cache.cluster.multicast.ip为广播IP地址
cache.cluster.properties为集群属性

配置例子:
cache.memory=true
cache.key=__oscache_cache
cache.path=/data/oscache
cache.capacity=100000
cache.unlimited.disk=true


5.OSCache的基本用法

cache1.jsp 内容如下
<%@ page import="java.util.*" %>
<%@ taglib uri="oscache" prefix="cache" %>
<html>
<body>
没有缓存的日期: <%= new Date() %><p>
<!--自动刷新-->
<cache:cache time="30">
每30秒刷新缓存一次的日期: <%= new Date() %>
</cache:cache>
<!--手动刷新-->
<cache:cache key="testcache">
手动刷新缓存的日期: <%= new Date() %> <p>
</cache:cache>
<a href="cache2.jsp">手动刷新</a>
</body>
</html>


cache2.jsp 执行手动刷新页面如下
<%@ taglib uri="oscache" prefix="cache" %>
<html>
<body>
缓存已刷新...<p>
<cache:flush key="testcache" scope="application"/>
<a href="cache1.jsp">返回</a>
</body>
</html>



你也可以通过下面语句定义Cache的有效范围,如不定义scope,scope默认为Applcation
<cache:cache time="30" scope="session">
...
</cache:cache>


6. 缓存过滤器 CacheFilter
   你可以在web.xml中定义缓存过滤器,定义特定资源的缓存。
 
<filter>
<filter-name>CacheFilter</filter-name>
<filter-class>com.opensymphony.oscache.web.filter.CacheFilter</filter-class>
<init-param>
<param-name>time</param-name>
<param-value>60</param-value>
</init-param>
<init-param>
<param-name>scope</param-name>
<param-value>session</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CacheFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping> 

上面定义将缓存所有.jsp页面,缓存刷新时间为60秒,缓存作用域为Session
注意,CacheFilter只捕获Http头为200的页面请求,即只对无错误请求作缓存,
而不对其他请求(如500,404,400)作缓存处理
  
7.关于oscache的几个基础方法:

public abstract class BaseManager<T extends BaseObject> implements Manager<T> {

    private static Log logger = LogFactory.getLog(BaseManager.class);
   
    private Cache oscache;
    public Cache getOscache() {
        return oscache;
    }
    public void setOscache(Cache oscache) {
        this.oscache = oscache;
    }
    protected final String createCachekey(Object keyParams[]) {
        if (keyParams == null) {
            return "";
        }

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < (keyParams.length - 1); i++) {
            sb.append(keyParams[i].toString()).append("':'");
        }

        return sb.append(keyParams[keyParams.length - 1]).toString();
    }

    public Object getCacheValue(String key) {
        return getCacheValue(key, null);
    }

    public Object getCacheValue(String key, Object obj) {
        Object new_obj = null;

        try {
            new_obj = oscache.getFromCache(key);
        } catch (NeedsRefreshException nre) {
            oscache.cancelUpdate(key);

            if (logger.isWarnEnabled()) {
                logger.warn("Failed to get from Cache");
            }
        }

        return (new_obj != null) ? new_obj : obj;
    }

    public void setCache(String key, Object serial) {
        setCache(key, serial, default_cache_time_second);
    }

    public void setCache(String key, Object serial, int cache_time) {
        if (oscache != null) {
            oscache.putInCache(key, serial, new ExpiresRefreshPolicy(cache_time));
        }
    }

    public void delCache(String key) {
        if (oscache != null) {
            oscache.removeEntry(key);
        }
    }

    public void flushCache(String key) {
        if (oscache != null) {
            oscache.flushEntry(key);
        }
    }
 }
分享到:
评论

相关推荐

    hibernate+oscache实现二级缓存实例

    非常实用的一个例子,有关于缓存对象 list 或缓存地址或jsp或其它页面,在实例中都有,须望可以帮到大家

    Hibernate OSCache缓存

    Hibernate OSCache缓存 Hibernate OSCache缓存

    hibernate_5.1包

    hibernate各个包 ...hibernate-oscache: 支持oscache的缓冲解决方案。(OSCache标记库由OpenSymphony设计,它是一种开创性的JSP定制标记应用,提供了在现有JSP页面之内实现快速内存缓冲的功能。 O

    struts2.3 spring 3.1 hibernate4.1 最新ssh oscache直接导入eclipse

    struts2.3 spring 3.1 hibernate4.1 最新ssh oscache直接导入eclipse就可以运行,还有一个项目带有spring-security-3.0.7 的,有需要的请给我留言,等过几天了,再拿出来给大家参考参考

    Oscache-入门教程.doc

    Cache是一种用于提高系统响应速度、改善系统运行性能的技术。尤其是在Web应用中,通过缓存页面的输出结果...Oscache的使用非常方便,特别是jsp cache用的非常广泛。Oscache的文档中也对jsp cache tag的配置有详细说明。

    OSCache使用说明

    OSCache是当前运用最广的缓存方案, Hibernate,jsp,页面等都对其有支持,下面简单介绍一下OSCache的配置和使用过程

    搭建hibernate的相关Jar包

    oscache-2.1.jar ojdbc14.jar log4j-1.2.16.jar jta-1.1.jar jbosscache-core-3.1.0.GA.jar jboss-cache-1.4.1.GA.jar javassist-3.9.0.GA.jar hibernate3.jar ehcache-1.2.3.jar dom4j-1.6.1.jar commons-lang-2.3....

    hibernate 3中的缓存小结

    l OSCache:可作为进程范围的缓存,存放数据的物理介质可以是内存或硬盘,提供了丰富的缓存数据过期策略,对Hibernate的查询缓存提供了支持。 l SwarmCache:可作为群集范围内的缓存,但不支持Hibernate的查询缓存。...

    Hibernate_二级缓存总结

    查询缓存的配置和使用: 1. 启用查询缓存:在 hibernate .cfg.xml 中加入: ”hibernate .cache.use_query_cache”&gt;true&lt;/property&gt; 2. 在程序中必须手动启用查询缓存,如: query.setCacheable(true); Query...

    hibernate+spring+struts2

    (2)运用struts1.2+hibernate+spring 框架,数据库连接池,事务管理; (3)Struts 应用国际化,Struts 标签库与Tiles框架, JSTL标签库,Spring IOC; (4)采用优化性能技术,采用oscache缓存,freemarker静态页面生成; (5)...

    SpringMVC+Hibernate全注解整合

    对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 mvc:annotation-driven --&gt; &lt;!-- 扫描包 --&gt; &lt;context:annotation-config/&gt; *" /&gt; ...

    Struts2+Spring2.5+Hibernate3+Freemarker框架整合

    整合S2SH+Freemarker+oscache,后台用Spring管理各个bean,Hibernate做数据库持久化,viewer用Freemarker。整合中对Struts2,Hibernate,Spring都采用Annotation进行注解类。

    hibernate3.1 jar包

    - OpenSymphony OSCache - runtime, optional asm.jar (unknown) - ASM bytecode library - runtime, required ant-launcher-1.6.5.jar (1.6.5) - Ant launcher - buildtime jaas.jar (unknown) - Standard JAAS ...

    (2.0版本)自己写的struts2+hibernate+spring实例

    所以没有上传导入的jar,其实就是默认的struts2和hibernate以及spring的包.该项目使用的jar包为以下. spring-beans.jar xwork-2.0.4.jar spring-context.jar ognl-2.6.11.jar spring-web.jar ...

    运用struts1.2+hibernate+spring 框架完整购物商城项目(内含sql文件)

    一个J2EE购物网站的实现 运用struts1.2+hibernate+spring 框架,数据库连接池,事务管理;Struts 应用国际化,Struts 标签库与Tiles框架, JSTL标签库,Spring IOC。 采用优化性能技术,采用oscache缓存,freemarker静态...

    JSP 开发之hibernate配置二级缓存的方法

    JSP 开发之hibernate配置二级缓存的方法 hibernate二级缓存也称为进程级的缓存或SessionFactory级的缓存。 二级缓存是全局缓存,它可以被... OSCache:可作为进程范围的缓存,存放数据的物理介质可以是内存或硬盘,提

    Java小说系统 V1.0 Beta

    2:采用Java开源的Oscache为网站进行缓存,默认对首页和列表页进行缓存,可以在Web.Xml中进行配置。 3.采用后台添加采集规则,对小说进行采集,简单方便,不用另外使用插件就可以采集小说内容。 使用环境: ...

    ssh整合例子(spring3 + struts2 + hibernate4+dwr+ext+json)

    内含 ext+dwr+freemark+jasperreort+ireport+echance+oscache+velocite等技术 展示例子:http://zz563143188.iteye.com/blog/1462413 若要下载chm格式请到http://user.qzone.qq.com/563143188 程序源码下载地址10MB...

Global site tag (gtag.js) - Google Analytics