Hibernate 프레임워크의 캐시 기술 상세 정보

8201 단어 Hibernate캐시
본고는 Hibernate 프레임워크의 캐시 기술을 실례로 다루고 있다.다음과 같이 여러분에게 참고할 수 있도록 공유합니다.
Hibernate 프레임워크의 캐시는 Session의 캐시, SessionFactory의 캐시로 나뉘는데 일급 캐시와 이급 캐시라고도 부른다.
1 레벨 캐시:
1 레벨 캐시는 Session 레벨의 캐시로 생명 주기가 매우 짧고 Session과 서로 대응하며 Hibernate가 관리하고 업무 범위에 속하는 캐시입니다.프로그램이 Session의load()방법,get()방법,save()방법,saveOrUpdate()방법,update()방법 또는 조회인터페이스방법을 호출할 때 Hibernate는 실체 대상을 캐시합니다.load () 방법이나 get () 방법을 통해 실체 대상을 조회할 때 Hibernate는 먼저 캐시에 가서 조회합니다. 실체 이미지를 찾을 수 없는 상황에서 Hibernate는 데이터베이스에 SQL 문장을 보내서 Hibernate의 사용 효율을 높일 수 있습니다.
예를 들어 말하자면

package com.xqh.util;
import org.hibernate.Session;
import com.xqh.model.User;
public class Test {
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSession(); //  session
session.beginTransaction(); // 
System.out.println(" :");
User user = (User)session.get(User.class, new Integer(1));
System.out.println(" :" + user.getName());
System.out.println(" :");
User user1 = (User)session.get(User.class, 1);
System.out.println(" :" + user1.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
//  
session.getTransaction().rollback();
} finally {
//  Session 
HibernateUtil.closeSession(session);
}
}
}

프로그램이 get() 방법을 통해 사용자 대상을 처음 찾을 때 Hibernate는 SQL 문장을 보내서 조회합니다. 이때 Hibernate는 사용자 대상에 대해 1급 캐시를 합니다.get () 방법으로 다시 조회할 때, Hibernate는 SQL 문장을 보내지 않습니다. 사용자 이름이 이미 1급 캐시에 존재하기 때문입니다.프로그램 실행 결과:

 :
Hibernate: 
select
user0_.id as id0_0_,
user0_.name as name0_0_,
user0_.sex as sex0_0_ 
from
tb_user_info user0_ 
where
user0_.id=?
 :xqh
 :
 :xqh

참고: 1레벨 캐시의 라이프 사이클은 Session과 상응하며 Session 간에 공유되지 않으며 다른 Session에서는 다른 Session에서 캐시된 실체 대상을 얻을 수 없습니다.
2 레벨 캐시:
2단계 캐시는 SessionFactory 레벨의 캐시로 수명주기는 SessionFactory와 일치합니다.2단계 캐시는 여러 세션 간에 공유할 수 있으며 프로세스 범위 또는 클러스터 범위에 속하는 캐시입니다.
2 레벨 캐시는 타사 캐시 제품의 지원이 필요한 플러그 가능한 캐시 플러그인입니다.Hibernate 프레임워크에서 Hibernate 프로필을 통해 2단계 캐시 사용 정책을 설정합니다.
1. 캐시 프로필 ehcache를 추가합니다.xml

<ehcache>
<!-- Sets the path to the directory where cache .data files are created.
If the path is a Java System Property it is replaced by
its value in the running VM.
The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="java.io.tmpdir"/>
<!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.
The following attributes are required for defaultCache:
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<!--Predefined caches. Add your cache configuration settings here.
If you do not have a configuration for your cache a WARNING will be issued when the
CacheManager starts
The following attributes are required for defaultCache:
name - Sets the name of the cache. This is used to identify the cache. It must be unique.
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
-->
<!-- Sample cache named sampleCache1
This cache contains a maximum in memory of 10000 elements, and will expire
an element if it is idle for more than 5 minutes and lives for more than
10 minutes.
If there are more than 10000 elements it will overflow to the
disk cache, which in this configuration will go to wherever java.io.tmp is
defined on your system. On a standard Linux system this will be /tmp"
-->
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<!-- Sample cache named sampleCache2
This cache contains 1000 elements. Elements will always be held in memory.
They are not expired. -->
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/> -->
<!-- Place configuration for your caches following -->
</ehcache>

2. Hibernate 프로필을 설정합니다.

<!--   -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!--   -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!--   -->
<class-cache class="com.xqh.model.User" usage="read-only"></class-cache>

예:

package com.xqh.util;
import org.hibernate.Session;
import com.xqh.model.User;
public class Test {
public static void main(String[] args) {
Session session = null; //  Session
try {
session = HibernateUtil.getSession();
session.beginTransaction();
System.out.println(" :");
User user = (User)session.get(User.class, 1);
System.out.println(" :" + user.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
//  
session.getTransaction().rollback();
} finally {
//  Session 
HibernateUtil.closeSession(session);
}
try {
session = HibernateUtil.getSession(); //  
session.beginTransaction();
System.out.println(" :");
User user = (User)session.get(User.class, 1);
System.out.println(" :" + user.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
//  
session.getTransaction().rollback();
} finally {
//  Session 
HibernateUtil.closeSession(session);
}
}
}

2단계 캐시는 Session 간에 공유되기 때문에 서로 다른 Session에서 같은 대상을 불러올 수 있습니다. Hibernate는 SQL 문장만 보내고 두 번째 대상을 불러올 때 Hibernate는 캐시에서 이 대상을 가져옵니다.
프로그램 결과:

 :
Hibernate: 
select
user0_.id as id0_0_,
user0_.name as name0_0_,
user0_.sex as sex0_0_ 
from
tb_user_info user0_ 
where
user0_.id=?
 :xqh
 :
 :xqh

2급 캐시에 대해 자주 업데이트되지 않는 데이터나 참고 데이터를 사용할 수 있는데 이때 그 성능은 뚜렷하게 향상될 것이다.그러나 자주 변화하는 데이터에 2단계 캐시를 적용하면 성능에 문제가 생길 수 있다.
본고에서 기술한 바와 같이 Hibernate 프레임워크를 바탕으로 하는 자바 프로그램 설계에 도움이 되기를 바랍니다.

좋은 웹페이지 즐겨찾기