首页 > 其他分享 >Hibernate和 OsCache的使用

Hibernate和 OsCache的使用

时间:2023-06-04 14:34:50浏览次数:52  
标签:缓存 OsCache color cache jar Hibernate 使用 OSCache oscache


下载地址:[url]http://java.net/downloads/oscache/[/url]

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



[color=red][b]hibernate使用OSCache[/b][/color][url]http://www.verydemo.com/demo_c146_i3116.html[/url]


拷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">





[b][color=red]OSCache - 在Hibernate中应用[/color][/b]


OSCache - 在Hibernate中使用


创建一个Java工程OSCacheTest,在其中引入Hibernate 3.2的类库文件。因为需要使用OSCache,还需要引入oscache-2.1.jar包。


一般使用OSCache缓存需要进行三个步骤的配置,具体如下:


[color=red][b]步骤一:在Hibernate中配置OSCache[/b][/color]


1. 在Hibernate配置文件中打开二级缓存的配置,如下:


<property name="cache.use_second_level_cache">true</property>


2. 这个值在配置文件中,缺省是打开的。这只是打开二级缓存,并没有指定使用哪个二级缓存。所以需要指定使用的何种二级缓存。配置如下:


<property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>


特别注意:关于二级缓存的配置,必须在<mapping resource="…………" />配置之前,否则报错



[color=red][b]步骤二:配置OSCache配置文件[/b][/color]


关于缓存中存放多少数据,Hibernate是不关心的,全部由OSCache来完成。需要将OSCache的配置文件oscache.properties放入classpath中(注意不能修改这个文件名),对二级缓存进行具体配置。


在oscache.properties中,有如下的参数配置:cache.capacity=1000


这个数值代表放入缓存的对象数量,这个数量根据用户机器的内存来配置,一般只需要配置这个参数即可。



[color=red][b]步骤三:通知Hibernate那些类需要OSCache进行缓存[/b][/color]


这个步骤有两种方式可以使用,其作用相同:


第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个值可以配置:


[color=blue]read-only:[/color]只读,缓存效率最高,用于不更新的数据


[color=blue]read-write:[/color]可读写


[color=blue]nonstrict-read-write:[/color]用于不重视并发修改的操作(会出现一定的错误数据,即不同步数据)


[color=blue]transactional:[/color]事务缓存,可支持事务回滚(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;
	}
}




[color=red][b]OSCache----Hibernate和 OsCache的使用[/b][/color]


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目录。



现在你的应用目录类似如下:


[i]$WEB_APPLICATION/WEB-INF/lib/oscache.jar


$WEB_APPLICATION/WEB-INF/classes/oscache.properties


$WEB_APPLICATION/WEB-INF/classes/oscache.tld[/i]



将下列代码加入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 文件内容为:


[i]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[/i]




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 文件配置向导


[b]cache.memory[/b]


值为true 或 false ,默认为在内存中作缓存,


如设置为false,那cache只能缓存到数据库或硬盘中,那cache还有什么意义:)


[b]cache.persistence.class[/b]


持久化缓存类,如此类打开,则必须设置cache.path信息


[b]cache.capacity[/b]


缓存元素个数


[b]cache.cluster 相关[/b]


为集群设置信息。




[b]cache.cluster.multicast.ip[/b]为广播IP地址


[b]cache.cluster.properties[/b]为集群属性



配置例子:


[b]cache.memory=true


cache.key=__oscache_cache


cache.path=/data/oscache


cache.capacity=100000


cache.unlimited.disk=true[/b]



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);
        }
    }
 }

标签:缓存,OsCache,color,cache,jar,Hibernate,使用,OSCache,oscache
From: https://blog.51cto.com/u_3871599/6410599

相关文章

  • oscache缓存技术
    oscache缓存技术:[url]http://j2eemylove.iteye.com/blog/939828[/url][b]1、OSCache是什么?[/b]OSCache标记库由OpenSymphony设计,它是一种开创性的缓存方案,它提供了在现有JSP页面之内实现内存缓存的功能。OSCache是个一个被广泛采用的高性能的J2EE缓存框架,OSCache还能应用于......
  • hibernate中自定义主键生成器
    自定义hibernate主键生成机制[url]http://walle1027.iteye.com/blog/1114824[/url]org.hibernate.id.MultipleHiLoPerTableGenerator主键生成器[url]http://suzefeng8806.iteye.com/blog/923511[/url][url]http://zhongrf.iteye.com/blog/972303[/url]......
  • react中reduce基本使用
    importReact,{useReducer}from'react';import'./App.css';constApp=()=>{constreduce=(state,action)=>{constactionFn={add:function(){return{...state,count:state.count+1}......
  • git的基本使用
    git的基本使用在git的命令行下,linux格式的命令是被接受的一.配置用户名和用户邮箱使用gitconfig--globaluser.name配置全局用户名,带参数就是配置,不带参数就是查看使用gitconfig--globaluser.email配置全局用户邮箱也可以在用户目录下的.gitconfig文件里添加......
  • hibernate------hql总结
    第14章HQL:Hibernate查询语言[url]http://www.redsaga.com/hibernate-ref/3.x/zh-cn/html/queryhql.html[/url][url]http://kuangbaoxu.iteye.com/blog/193076[/url][color=red][b]1.查询整个映射对象所有字段[/b][/color]//直接from查询出来的是一......
  • spring jdbcTemplate使用
    参考:springjdbcTemplate使用[url]http://log-cd.iteye.com/blog/215059[/url]SpringJdbcTemplate与事务管理学习[url]http://www.iteye.com/topic/480432[/url]SimpleJdbcTemplate在spring3.1已经过时了,我就改为使用jdbcTemplate和namedParameterJdbcOperations写sql查询......
  • Hibernate性能调优,优化
    Hibernate优化_Hibernate性能优化_Hibernate优化方案(上):[url]http://xiexiejiao.cn/hibernate/hibernate-performance-optimization-a.html[/url]Hibernate优化_Hibernate性能优化_Hibernate优化方案(下):[url]http://xiexiejiao.cn/hibernate/hibernate-performance-optimizati......
  • Hibernate Tools生成Hibernate Mapping文件及PO类
    [color=red][b]本文参考[/b][/color]:HowToGenerateHibernateMappingFiles&AnnotationWithHibernateTools[url]http://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/[/url]eclipse利用HibernateTools生成HibernateMap......
  • 在 VS Code 中使用 GitHub Actions 以及 在仓库中创建一个 .github/workflows 目录
    在VSCode中使用GitHubActions需要完成以下步骤:1.首先,需要在GitHub上创建一个仓库,并在仓库中创建一个`.github/workflows`目录,用于存放GitHubActions的工作流文件。2.在VSCode中打开该仓库,并在左侧的“资源管理器”中选择`.github/workflows`目录。3.右键......
  • SpringSecurity使用JWT
    SpringSecurity的UsernamePasswordAuthenticationFilter用于处理认证。要整合JWT,只需在认证成功后生成TOKEN并通过响应头写回客户端。在新增一个过滤器用于校验TOKEN。新建SpringBoot项目,添加依赖:<dependency><groupId>org.springframework.boot</groupId>......