十一、Hibernate高级配置 C3P0连接池、Log4j日志框架 二级缓存EHCache

Hibernate C3P0配置:

引入C3PO包

在hibernate.cfg.xml文件中配置:

<!-- 数据库连接池的使用 -->
<!-- 选择使用C3P0连接池 -->
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
<!-- 连接池中最小连接数 -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- 连接池中最大连接数 -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- 设定数据库连接超时时间,以秒为单位。如果连接池中某个数据库连接处于空闲状态且超过timeout秒时,就会从连接池中移除-->
<property name="hibernate.c3p0.timeout">120</property>
<!-- 设置数据库 -->
<property name="hibernate.c3p0.idle_test_period">3000</property>

C3P0其他配置:

1 <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
  2 <property name="acquireIncrement">3</property>
  3 <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
  4 <property name="acquireRetryAttempts">30</property>
  5 <!--两次连接中间隔时间,单位毫秒。Default: 1000 -->
  6 <property name="acquireRetryDelay">1000</property>
  7 <!--连接关闭时默认将所有未提交的操作回滚。Default: false -->
  8 <property name="autoCommitOnClose">false</property>
  9 <!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么
 10 属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试
 11 使用。Default: null-->
 12 <property name="automaticTestTable">Test</property>
 13 <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
 14 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
 15 获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->
 16 <property name="breakAfterAcquireFailure">false</property>
 17 <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出
 18 SQLException,如设为0则无限期等待。单位毫秒。Default: 0 -->
 19 <property name="checkoutTimeout">100</property>
 20 <!--通过实现ConnectionTester或QueryConnectionTester的类来测试连接。类名需制定全路径。
 21 Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester-->
 22 <property name="connectionTesterClassName"></property>
 23 <!--指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得那么无需设置,默认null即可
 24 Default: null-->
 25 <property name="factoryClassLocation">null</property>
 26 <!--Strongly disrecommended. Setting this to true may lead to subtle and bizarre bugs.
 27 (文档原文)作者强烈建议不使用的一个属性-->
 28 <property name="forceIgnoreUnresolvedTransactions">false</property>
 29 <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
 30 <property name="idleConnectionTestPeriod">60</property>
 31 <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
 32 <property name="initialPoolSize">3</property>
 33 <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
 34 <property name="maxIdleTime">60</property>
 35 <!--连接池中保留的最大连接数。Default: 15 -->
 36 <property name="maxPoolSize">15</property>
 37 <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
 38 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
 39 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
 40 <property name="maxStatements">100</property>
 41 <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
 42 <property name="maxStatementsPerConnection"></property>
 43 <!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能
 44 通过多线程实现多个操作同时被执行。Default: 3-->
 45 <property name="numHelperThreads">3</property>
 46 <!--当用户调用getConnection()时使root用户成为去获取连接的用户。主要用于连接池连接非c3p0
 47 的数据源时。Default: null-->
 48 <property name="overrideDefaultUser">root</property>
 49 <!--与overrideDefaultUser参数对应使用的一个参数。Default: null-->
 50 <property name="overrideDefaultPassword">password</property>
 51 <!--密码。Default: null-->
 52 <property name="password"></property>
 53 <!--定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:
 54 测试的表必须在初始数据源的时候就存在。Default: null-->
 55 <property name="preferredTestQuery">select id from test where id=1</property>
 56 <!--用户修改系统配置参数执行前最多等待300秒。Default: 300 -->
 57 <property name="propertyCycle">300</property>
 58 <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的
 59 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
 60 等方法来提升连接测试的性能。Default: false -->
 61 <property name="testConnectionOnCheckout">false</property>
 62 <!--如果设为true那么在取得连接的同时将校验连接的有效性。Default: false -->
 63 <property name="testConnectionOnCheckin">true</property>
 64 <!--用户名。Default: null-->
 65 <property name="user">root</property>
 66 在Hibernate(spring管理)中的配置:
 67 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
 68 <property name="driverClass"><value>oracle.jdbc.driver.OracleDriver</value></property>
 69 <property name="jdbcUrl"><value>jdbc:oracle:thin:@localhost:1521:Test</value></property>
 70 <property name="user"><value>Kay</value></property>
 71 <property name="password"><value>root</value></property>
 72 <!--连接池中保留的最小连接数。-->
 73 <property name="minPoolSize" value="10" />
 74 <!--连接池中保留的最大连接数。Default: 15 -->
 75 <property name="maxPoolSize" value="100" />
 76 <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
 77 <property name="maxIdleTime" value="1800" />
 78 <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
 79 <property name="acquireIncrement" value="3" />
 80 <property name="maxStatements" value="1000" />
 81 <property name="initialPoolSize" value="10" />
 82 <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
 83 <property name="idleConnectionTestPeriod" value="60" />
 84 <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
 85 <property name="acquireRetryAttempts" value="30" />
 86 <property name="breakAfterAcquireFailure" value="true" />
 87 <property name="testConnectionOnCheckout" value="false" />
 88 </bean>
 89 编辑本段相关信息连接池配置(以Hibernate为例)
 90 ###########################
 91 ### C3P0 Connection Pool###
 92 ###########################
 93 #hibernate.c3p0.max_size 2
 94 #hibernate.c3p0.min_size 2
 95 #hibernate.c3p0.timeout 5000
 96 #hibernate.c3p0.max_statements 100
 97 #hibernate.c3p0.idle_test_period 3000
 98 #hibernate.c3p0.acquire_increment 2
 99 #hibernate.c3p0.validate false
100 在hibernate.cfg.xml文件里面加入如下的配置:
101 <!-- 最大连接数 -->
102 <property name="hibernate.c3p0.max_size">20</property>
103 <!-- 最小连接数 -->
104 <property name="hibernate.c3p0.min_size">5</property>
105 <!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
106 <property name="hibernate.c3p0.timeout">120</property>
107 <!-- 最大的PreparedStatement的数量 -->
108 <property name="hibernate.c3p0.max_statements">100</property>
109 <!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒-->
110 <property name="hibernate.c3p0.idle_test_period">120</property>
111 <!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->
112 <property name="hibernate.c3p0.acquire_increment">2</property>
113 <!-- 每次都验证连接是否可用 -->
114 <property name="hibernate.c3p0.validate">true</property>

Hibernate 配置Log4j

1.在项目中引入 log4j 的jar包

2.配置log4j.properties文件:

log4j.rootLogger=debug,appender1,appender2

log4j.appender.appender1=org.apache.log4j.ConsoleAppender 

log4j.appender.appender2=org.apache.log4j.FileAppender 
log4j.appender.appender2.File=E:/logFile.txt
 
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout  

3.在测试类中初始化log方法 , 进行日志输出。

关于 log4j详细的知识点 可以参考: log4j.properties 详解与配置步骤 这篇文章,讲得很详细。

配置 Hibernate  二级缓存

 

缓存的概念:

缓存是介于物理数据源与应用程序之间,是对数据库中的数据复制一份临时放在内存或者硬盘中的容
器,其作用是为了减少应用程序对物理数据源访问的次数,从而提高了应用程序的运行性能。Hibernate 在进
行读取数据的时候,根据缓存机制在相应的缓存中查询,如果在缓存中找到了需要的数据(我们把这称做“缓
存命 中"),则就直接把命中的数据作为结果加以利用,避免了大量发送 SQL 语句到数据库查询的性能损耗。

 

Hibernate 缓存的分类:

Session 缓存(又称作事务缓存):Hibernate 内置的,不能卸除。
缓存范围:缓存只能被当前 Session 对象访问。缓存的生命周期依赖于 Session 的生命周期,当 Session 被关闭
后,缓存也就结束生命周期。

SessionFactory 缓存(又称作应用缓存):使用第三方插件,可插拔。
缓存范围:缓存被应用范围内的所有 session 共享,不同的 Session 可以共享。这些 session 有可能是并发访问缓
存,因此必须对缓存进行更新。缓存的生命周期依赖于应用的生命周期,应用结束时,缓存也就结束了生命
周期,二级缓存存在于应用程序范围。

二级缓存策略提供商:

提供了 HashTable 缓存,EHCache,OSCache,SwarmCache,jBoss Cathe2,这些缓存机制,其中 EHCache,
OSCache 是不能用于集群环境(Cluster Safe)的,而 SwarmCache,jBoss Cathe2 是可以的。HashTable 缓存主
要是用来测试的,只能把对象放在内存中,EHCache,OSCache 可以把对象放在内存(memory)中,也可以
把对象放在硬盘(disk)上(为什么放到硬盘上?上面解释了)

什么数据适合放二级缓存中:

(1)经常被访问
(2)改动不大
(3)数量有限
(4)不是很重要的数据,允许出现偶尔并发的数据。

Hibernate中的一级缓存:

我们参考之前的一对多的例子,假设现在 有一个班级:精英班   有两个学生:  孔明 、 子房

我们获取一下班级名称:

@Test
	public void testCache1() throws Exception {
		Class c1 = (Class) session.get(Class.class, 1);
		System.out.println(c1.getClaaName());
		Class c2 = (Class) session.get(Class.class, 1);
		System.out.println(c2.getClaaName());
		System.out.println(c1 == c2);
	}

看控制台,只发出一条sql,而且 c1 == c2 说明 c2是从session一级缓存中取得 ,直接从内存中拿 而没有查数据库。

上述是在同一个事务当中  我们试一下在不同事务中,是否还有session的一级缓存。

@Test
	public void testCache2() throws Exception {
		Session session1 = sessionFactory.openSession();
		session1.beginTransaction();
		Class c1 = (Class) session1.get(Class.class, 1);
		System.out.println(c1.getClaaName());
		session1.getTransaction().commit();
		session1.close();
		
		Session session2 = sessionFactory.openSession();
		session2.beginTransaction();
		Class c2 = (Class) session2.get(Class.class, 1);
		System.out.println(c2.getClaaName());
		session2.getTransaction().commit();
		session2.close();
		System.out.println(c1 == c2);
	}

看下面控制台 发出了两条sql,而且 c1 和 c2 不相等

说明session的一级缓存 只存在同一个session 同一个事务当中 不可以共用。

那我们如果能让它们共享呢?这就需要用到二级的SessionFactory缓存了。

配置 ehcache 

1.添加ehcache支持的jar 以及 ehcache.xml 文件配置:

ehcache.xml:

<ehcache>
   
   	<!-- 
5         磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
6         path:指定在硬盘上存储对象的路径
7      -->
    <diskStore path="c:\\ehcache"/>
    
    <!-- 
    	   name 设置缓存的名字,他的取值为类的完整名字或者类的集合的名字;
12         defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
13         maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
14         eternal:代表对象是否永不过期
15         timeToIdleSeconds:最大的发呆时间 以秒为单位;
16         timeToLiveSeconds:最大的存活时间 以秒为单位;
17         overflowToDisk:表示当基于内存的缓存中的对象数目达到maxElementsInMemory界限,会把溢出的对象写到基于硬盘的缓存中
18   -->   
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

	<!-- 设定具体的第二级缓存的数据过期策略 -->
    <cache name="com.tao.entity.Class"
        maxElementsInMemory="1"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />
 

</ehcache>

2. 在hibernate.cfg.xml中配置缓存相关配置:

 <!-- 启用二级缓存 -->
		<property name="cache.use_second_level_cache">true</property>
    	
    	<!-- 配置使用的二级缓存的产品 -->
    	<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
    	
    	<!-- 配置启用查询缓存 -->
    	<property name="cache.use_query_cache">true</property>

3.在需要使用缓存的类中 加上缓存配置:

然后再运行testCache2 测试方法,发现只会发出一条SQL 去数据库中查询,至此Hibernate 二级缓存配置成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值