In Memory Data Grid - Infinispan(JBoss Data Grid) 소개
-
Upload
opennaru-inc -
Category
Technology
-
view
3.205 -
download
9
description
Transcript of In Memory Data Grid - Infinispan(JBoss Data Grid) 소개
opennaru.com | 2013 | All Rights Reserved 1
About me
• 현재 오픈나루㈜
• 이전 직장
• Red Hat, Senior JBoss Consultant
• BEA Systems, Senior Developer Relations Engineer
• NEXTEL, Inc. GIS Engine 개발, Server Framework 개발 등
• 책
• 거침없이 배우는 JBoss - EAP 6(AS7), 저자
• Seam In Action, 공동 번역
• More about me?
• Blog : http://opennaru.blog.me
• Facebook : https://www.facebook.com/junshik.jeon
• Company : http://www.opennaru.com
• E-mail : [email protected] [email protected]
opennaru.com | 2013 | All Rights Reserved 2
Agenda
• Consistent Hashing 알고리즘
• The Origin
• 알고리즘
• 구현 방법
• In Memory Data Grid
• Use Cases
• References
• Infinispan(JBoss Data Grid)
• 주요 특징
• Library Mode & Server Mode
• Cache Topology
• Eviction & Expiration
• Cache Store
• Infinispan Code Sample
• Distributed Executor
• Map/Reduce
• Query
• Data Grid API(Transaction 등)
• Performance
• RadarGun 성능 측정
• Azul Zing + JBoss Data Grid
• 샘플 코드
• Simple PUT/GET
• XML설정 PUT/GET
• Spring Integration 샘플
• Queue 예제
• Live 서버 설치
• HotRod Client 샘플
opennaru.com | 2013 | All Rights Reserved 3
Header text
opennaru.com | 2013 | All Rights Reserved 4
BigData의 기원
http://infolab.stanford.edu/~backrub/google.html
opennaru.com | 2013 | All Rights Reserved 5
HBase의 기원
http://www.slideshare.net/ptdorf/bigtable-osdi06
Google’s LevelDB
opennaru.com | 2013 | All Rights Reserved 6
In Memory Data Grid(IMDG)
http://www8.org/w8-papers/2a-webserver/caching/paper2.html
1997
opennaru.com | 2013 | All Rights Reserved 7
Header text
opennaru.com | 2013 | All Rights Reserved 8
인터넷 서비스 시스템
인터넷
WAS서버 #1
데이터베이스 웹서버
WAS서버 #2
opennaru.com | 2013 | All Rights Reserved 9
데이터 캐시 서버 도입
인터넷
WAS서버 #1
데이터베이스 웹서버
WAS서버 #2
`
캐시서버
opennaru.com | 2013 | All Rights Reserved 10
여러 대의 캐시 서버
인터넷
WAS서버 #1 데이터베이스
웹서버
WAS서버 #2
`
캐시서버
opennaru.com | 2013 | All Rights Reserved 11
캐시 서버가 여러 대일 경우 데이터 분배 방법
hash(“opennaru”) % 3 + 1 = 37 % 3 + 1
= 2
1
2
3
캐시서버
KEY VALUE
opennaru 전준식
KHAN provisioning
KEY VALUE
opennaru 전준식
KEY VALUE
KHAN provisioning
opennaru.com | 2013 | All Rights Reserved 12
캐시 서버 장애 발생
인터넷
WAS서버 #1 데이터베이스
웹서버
WAS서버 #2
`
캐시서버
opennaru.com | 2013 | All Rights Reserved 13
캐시 서버 장애 발생시 데이터 분배
hash(“opennaru”) % 2 + 1 = 37 % 2 + 1
= 2
1
2
2
캐시서버
KEY VALUE
opennaru 전준식
KHAN provisioning
KEY VALUE
opennaru 전준식
KEY VALUE
KHAN provisioning
opennaru.com | 2013 | All Rights Reserved 14
캐시 서버 장애 발생
인터넷
WAS서버 #1 데이터베이스
웹서버
WAS서버 #2
캐시서버
opennaru.com | 2013 | All Rights Reserved 15
Consistent Hashing
Const_hash(“opennaru”) = 27 0
32 59
27
Const_hash(“KHAN”) = 45
45
1 2
3
Hash Ring(Hash Wheel)
opennaru.com | 2013 | All Rights Reserved 16
Consistent Hashing
Const_hash(“opennaru”) = 27 0
32 59
27
Const_hash(“KHAN”) = 45
45
1 2
3
Hash Ring(Hash Wheel)
opennaru.com | 2013 | All Rights Reserved 17
Consistent Hashing
Const_hash(“opennaru”) = 27 0
32 59
27
Const_hash(“KHAN”) = 45
45
1 2
3
Hash Ring(Hash Wheel)
27
45
opennaru.com | 2013 | All Rights Reserved 18
Header text
opennaru.com | 2013 | All Rights Reserved 19
Consistent Hashing 샘플 코드
http://www.tom-e-white.com/2007/11/consistent-hashing.html
opennaru.com | 2013 | All Rights Reserved 20
Segments(Virtual Nodes, Replicas)
opennaru.com | 2013 | All Rights Reserved 21
Consistent Hashing 샘플 코드
opennaru.com | 2013 | All Rights Reserved 22
Infinispan(JBoss Data Grid)에서는
• Hash 공간은 32bit Integer로 구성됨
• -21억 ~ +21억 개
• 노드의 불균형은 통계적으로 노드의 개수가 100~200개 정도가 되면 해소됨
• 예를 들어 클러스터 노드가 4개이면 segments(virtual-nodes)를 50개로 설정하면
• 4 x 50 = 200개의 총 노드가 사용됨
<namedCache name=“cacheName">
<clustering>
<hash numOwners="2" numSegments=“50" />
</clustering>
</namedCache>
opennaru.com | 2013 | All Rights Reserved 23
이론적 속도는?
• B Tree
𝑶 𝒍𝒐𝒈 𝒏
• Hash table
𝑶 𝟏 ~ 𝑶 ( 𝒏 )
• Distributed Hash table
𝑶 𝒍𝒐𝒈 𝒏
http://en.wikipedia.org/wiki/B-tree
http://en.wikipedia.org/wiki/Hash_table
http://en.wikipedia.org/wiki/Distributed_hash_table
opennaru.com | 2013 | All Rights Reserved 24
Header text
opennaru.com | 2013 | All Rights Reserved 25
• NoSQL 데이터베이스 : 분산 아키텍처의 확장성 등의 요구 사항을 충족하며, 스키마 없는 데이터 관리 요구 사항에 부합하도록 설계됨
• NewSQL 데이터베이스 : 분산 아키텍처의 확장성 등의 요구 사항을 충족하거나, 수평 확장을 필요로 하지 않지만 성능이 개선되도록 설계됨(Ex, New MySQL Storage Engine, Sharding 등 지원)
• Data Grid/Cache 제품 : 응용 프로그램 및 데이터베이스 성능을 높이기 위해 메모리에 데이터를 저장하도록 설계됨. (Non) Persistent, Compute Grid 기능
Evolving DB Landscape
Data grid/cache products designed to store data in
memory to increase application and database
performance, covering a spectrum of data
management capabilities from non-persistent data
caching to persistent caching, replication, and
distributed data and compute grid functionality
– Matthew Aslett,
senior analyst at the 451 group
Source : NoSQL, NewSQL and Beyond: The answer to SPRAINed relational databases http://blogs.the451group.com/information_management/2
011/04/15/nosql-newsql-and-beyond/
opennaru.com | 2013 | All Rights Reserved 26
In memory storage engines
Distributed across a cluster providing
“networked memory”
Pacemakers to databases
Provide simple key,value storage
Linear scalability and elasticity due to distributed
algorithms
What is a Data Grid
opennaru.com | 2013 | All Rights Reserved 27
Header text
opennaru.com | 2013 | All Rights Reserved 28
• 고가의 데이터베이스 시스템에 성능이나 장애로부터 애플리케이션 서버를 분리하여 고 안정성을 보장을 할 수 있는 방안은?
• 고가의 데이터베이스 확장에 대한 비용 부담으로 부터 저비용고효율 시스템 아키텍처로 전환하려는 요구는 ?
데이터베이스의 성능 종속성 탈피 방안
사용자 응답 속도와 서비스 품질 보장 방안 – 데이터베이스 이슈
스케일 아웃형 이슈
• 데이터베이스의
스케일아웃 구조로
인한 비용 부담
• DB 라이선스 비용
DB 병목
• DB I/O 증가에 따른
성능 감소
• 불필요한 중복 쿼리
발생
• 오래 걸리는 쿼리
DB 성능과 응답시간
• 데이터베이스의 성
능에 영향 없이 일정
한 서비스 응답 속도
를 보장 방안 있는가?
예측 가능한 확장
• 데이터 양의 증가나
사용자 증가에 따른
예측 가능한 확장성
확보 방안이 있는가?
DB 성능에 따라 전체 서비스의 응답속도와 장애가 발생되는가?
opennaru.com | 2013 | All Rights Reserved 29
분산 데이터그리드를 통한 DB 부하 절감 - 콘텐트
DB 병목
사용자 증가에 따른 데이터베이스의 부하 증가
페이지의 동적인 정보는 모두 데이터베이스로
쿼리
기존 애플리케이션을 수정하지 않고 메모리 캐쉬
적용 요구
효율적인 투자 모델 및 계획 요구
데이터그리드 기반의 쿼리 오프로드
5초 단위로 데이터베이스 요청 감소
캐쉬 Flush를 통한 데이터 베이스와 자동 동기화
캐쉬에 대한 로컬/분산/하이브리드
형태의 다양한 저장 구조 확보
손쉬운 캐쉬 적용
…..
최다조회뉴스
최다 코멘트 뉴스
추천 뉴스
분야별 주요 뉴스
포토 뉴스
가장 많이 본 뉴스
실시간 급상승 뉴스
…..
최다조회뉴스
최다 코멘트 뉴스
추천 뉴스
분야별 주요 뉴스
포토 뉴스
가장 많이 본 뉴스
실시간 급상승 뉴스
DataGrid #1
DataGrid #2
DataGrid #3
DataGrid #4
A
B
C
D
C
D
B
A
opennaru.com | 2013 | All Rights Reserved 30
데이터그리드를 통한 GeoLocation 서비스 - DB 부하 절감
Service Platform
GeoLocation은 웹브라우저/ TV/ 모바일 디바이스에서 접속 시 IP 정보를 통해 접속 위치를 파악하여 서비스 가능
여부를 파악
TV 나 모바일 디바이스의 경우 페이지 요청 시 마다 데이터베이스에 GeoLocation을 요청하여 불필요한 부하 발생
DB 기반 GeoLocation 정보 Datagrid 기반 GeoLocation 정보
Service Platform
JBoss DataGrid
GeoLocation table GeoLocation table
데이터그리드에 조건을 주어 지역별 서비스 가능 여부를 파악
매일 오전에 GeoLocation 테이블로 부터 데이터그리드로 GeoLocation 정보를 업데이트
불필요한 DB 부하 제거
opennaru.com | 2013 | All Rights Reserved 31
웹 세션 클러스터링 구성
항목 WAS 내장 세션 관리 별도 세션 관리 서버 데이터그리드 기반 세션 관리
구현 방법 • 세션데이터별
Primary/Backup 인스턴스를 지정하여 공유
• 별도의 세션 서버 운영 • 데이터그리드에 세션 정보를 저
장하여 운영
장점 • 별도의 서버와 인프라 없이
가능 • 인스턴스간 애플리케이션간 세
션 공유 설정이 용이
• 인스턴스와 애플리케이션 간 세션 공유 용이
• Elasitc 확장성과 안정성 부장
단점
• 세션데이터의 백업 및 동기화 이슈
• WAS 인스턴스 장애와 함께 세션 복제의 이슈가 발생
• 단일 장애 지점과 별도의 서버 구성에 따른 비용
• 제한적인 안정성 • 낮은 성능
• 별도의 서버 구성으로 인한 비용 발생
• 관리 포인트 증가 • 메모리 기반 고성능
제품 • Weblogic • WebSphere
• JEUS • JBoss EAP( JBoss Data Grid) • Coherence*Web
WAS 간 구성 세션 서버 구성 세션 데이터그리드 구성
WAS WAS WAS WAS
WEB WEB WEB WEB
WAS WAS WAS WAS
WEB WEB WEB WEB
Session Clustering
세션 서버
백업
WAS WAS WAS WAS
WEB WEB WEB WEB
Session Clustering Session
Clustering
데이터 그리드
opennaru.com | 2013 | All Rights Reserved 32
Use Cases - References
• CBOE (Chicago Board of Options Exchange)
Biggest options trading exchange in the world. Primary trading platform’s high availability/failover features built on JDG.
• (Major international retail banking group, based in Madrid) – Real-time risk analysis systems with response time requirements of under 50 milliseconds, even during garbage collection.
• (Major UK retail and trading bank based in London) – Real-time risk analysis systems, trading platforms running on over 4000 servers.
• CISCO – Media streaming for 3DTV. DRM and ratings
management system. Highly distributed - and transactional - across 3 data centres. Next version will be embedded in set-top boxes.
• RIM (BlackBerry) – DRM and video-on-demand streaming systems.
• RealEstate.com.au – Largest property selling and letting portal in Australia and New Zealand. High-end e-commerce.
• (Major European insurance company) – Risk analysis, distributed caching of complex risk models.
http://jp.redhat.com/rhecm/rest-rhecm/jcr/repository/collaboration/sites%20content/live/redhat/web-cabinet/static-
files/documents/JBoss_SolutionSeminar-2_120712
opennaru.com | 2013 | All Rights Reserved 33
Header text
opennaru.com | 2013 | All Rights Reserved 34
Open Source(LGPL Apache 2.0) 데이터 그리드 제품
2008년에 프로젝트 시작, Java 언어와 Scala 언어를 이용
JBoss Cache 프로젝트를 대체하는 프로젝트
Amazon Dynamo와 유사한 개념으로 개발
두 가지 제품
라이브러리 모드
Client/Server 모드
Memcached
Hot Rod
REST
Infinispan(JBoss Data Grid 6)
34
opennaru.com | 2013 | All Rights Reserved 35
예측 가능한 확장성을 제공하는 데이터 그리드 플랫폼
네트워크상의 메모리 공유, 분산 프로세싱 전용으로 설계
인메모리로 동작하는 Key-Value형 데이터 스토어(KVS)
데이타베이스 프론트에 배치하여 대용량 데이터 캐쉬 역할
Data Grid로서 필요한 기능을 제공
투명한 수평 확장성 제공(신축성)
고속 데이터 액세스
네트워크 상의 거대한 heap 메모리로 사용
다양한 접속 프로토콜 지원
REST API, Memcache API 및 고속 처리용 API HotRod 이용 가능
여러 가지 클라이언트 환경에서 이용 가능
Java, Python나 Microsoft . NET등으로부터도 이용 가능
클라이언트 증가에 의한 추가 비용이 발생하지 않는 서브스크립션
JBoss Data Grid
opennaru.com | 2013 | All Rights Reserved 36
Infinispan(JBoss Data Grid) 주요 특징
기능 개요 설명
JTA Transaction 트랜잭션 지원 • Full XA 호환
CacheStore 데이터 영속화 • 데이터 영속화 보장
DistributedExecutors 분산 실행 기능 일반적인 태스크를 실행
• 데이터 저장 인스턴스에서 고속 병렬처리
MapReduce 분산 실행 기능 MapReduce 처리를 실행
• 데이터 저장 인스턴스에서 고속 병렬처리
QueryAPI 풀 텍스트 검색 엔진 기능 • 전체 서버 대상 고속 검색
GridFileSystem 메모리 파일 시스템 • 고속 파일 액세스
opennaru.com | 2013 | All Rights Reserved 37
Header text
opennaru.com | 2013 | All Rights Reserved 38
Infinispan(JBoss Data Grid)의 구성
• 라이브러리 모드
• 애플리케이션과 같은 VM에서 동작
• 다양한 설정 및 API로 상세한 제어 가능
• Java만 지원
• 보다 다양한 기능, API 제공
• 보다 고성능
• 클라이언트/서버 모드
• DataGrid 클러스터로 접속
• 애플리케이션에서 데이터레이어를 분리
• 서로 다른 언어 지원을 통한 통합
• 여러 가지 프로토콜 이용 가능
• Hot Rod, Memcached, REST
• 여러 애플리케이션에서 데이터그리드 공유 가능
opennaru.com | 2013 | All Rights Reserved 39
• 라이브러리 모드는 JDG 네이티브 기능을 사용할 수 있기 때문에 다양한 구현 방법 지원
Infinispan(JBoss Data Grid 6.2) – 2개 제품
EAP
DataGrid
EAP
DataGrid
EAP
DataGrid
EAP
DataGrid
클라이언트 서버 모드 라이브러리 모드
REST 인터페이스 ◎
Memcached 인터페이스 ◎
Hod Rod 클라이언트 ◎
JBoss Operations Network 모니터링 ◎
CDI ◎
비동기 API ◎
커스텀 인터셉터 ◎
리스너 모델 지원 ◎
트랜잭션(transaction) ◎
Map/Reduce API ◎
EWS
DataGrid
EWS
DataGrid
EWS
DataGrid
EWS
DataGrid
Datagrid Cluster Datagrid Cluster
Datagrid 라이브러리 모드 적용
opennaru.com | 2013 | All Rights Reserved 40
Header text
opennaru.com | 2013 | All Rights Reserved 41
분산 Topology (1/2)
Local Cache
• 인스턴스 끼리 데이터 공유 없이 각각 캐쉬 관리 • 다른 Cache 서버로 요청하지 않음
Cluster
Datagrid #1 Datagrid #2 Datagrid #3
Distribution Cache
• Dist Cache는 1/n로 데이터를 나누어 저장 • 데이터가 없을 경우 다른 Cache 서버로 요청
Cluster
Datagrid #1 Datagrid #2 Datagrid #3
Replication Cache
• 전체 데이터를 각자의 Cache 서버들이 저장 • 다른 Cache 서버로 요청하지 않음
Cluster
Datagrid #1 Datagrid #2
Datagrid #3
opennaru.com | 2013 | All Rights Reserved 42
분산 Topology (2/2)
Invalidation Cache
• 전체 데이터를 각자의 Cache 서버들이 저장 • 다른 Cache 서버로 요청하지 않음 • 데이터 변경 시 다른 서버의 동일 키를 삭제
Cluster
Datagrid #1 Datagrid #2 Datagrid #3
Cluster
Datagrid #1 Datagrid #2 Datagrid #3
Distribution
+ L1 Cache
• 성능을 위하여 Local Cache 에 정해진 개수 만큼을 저장 • Dist Cache는 1/n로 나누어 저장
opennaru.com | 2013 | All Rights Reserved 43
데이터 분산 모델
모드 방식 Read Write 확장성 설명
Local 복제 없음 고속 고속 없음 분산 되지 않고 클러스터 요건이 없는 데이터에 대한 단순 캐쉬
Replication 전체 복제 고속 저속 없음 캐쉬 사이즈 전체 사이즈가 고정된 경우
Distribution 일부 복제 약간 저속 약간 고속 높음 대용량 데이터나 대량 분산 병렬 처리 시 대용량읜 메모리를 사용해야 하는 경우
L1 Cache+ Distribution
일부 복제 약간 고속 약간 고속 높음 Distribution과 동일하며 각각의 인스턴스 별로 버퍼 캐쉬인 한 “Near Cache” 를 get 일 때 성능 향상
Invalidation 복제 없음 저속 고속 없음 데이터가 변경되었을 경우에 다른 인스턴스의 해당 데이터를 삭제
opennaru.com | 2013 | All Rights Reserved 44
• 같은 JVM 에서 데이터 저장
• 단순한 Java Map과 달리 다양한 JBoss Datagrid 기능 지원
• Local Mode 기능
• Write-through, Write-behind 캐쉬
• OOM를 막기 위한 Eviction
• Expiration
• 트랜잭션(transaction) 지원(JTA, XA)
• Non-Blocking 에 의한 고속의 읽기(MVCC 기반의 병렬처리)
• JMX나 JON에 의한 관리
Local Mode
Local Cache
• 인스턴스 끼리 데이터 공유 없이 각각 캐쉬 관리 • 다른 Cache 서버로 요청하지 않음
Cluster
Datagrid #1 Datagrid #2 Datagrid #3
opennaru.com | 2013 | All Rights Reserved 45
• Replication는 단순한 클러스터 모드로 캐쉬에 추가된 엔트리는 클러스터내의 다른 모든 캐쉬 인스턴스에 복제
• 클러스터 사이즈가 증가하는 것에 따라 replication message가 증가하기 때문에 비교적 작은 클러스터(10 서버 미만) 적용
Replication Mode
PUT는 클러스터 크기와 같은 횟수 리모트 호출이 발생
opennaru.com | 2013 | All Rights Reserved 46
• Distribution 는 강력한 클러스터링 모드로, 선형적인 스케일아웃이 필요한 대량의 클러스터 노드 환경에 적용
• Distribution는 클러스터 엔트리가 어디에 저장 될지를 결정하기 위해 Consistent Hash 알로리즘 적용
• 설정된 백업 수 만큼 클러스터에서 복제본을 저장
• 백업 수는 성능과 데이터 저장의 안정성과 트레이드 오프(기본값은 2)
• 멀티 캐스트나 메타데이타를 유지하지 않고 데이터 저장 위치 결정
Distribution Mode
·PUT는 지정된 백업 숫자만큼 발생 ·GET는 최대 1회의 리모트 호출이 발생 실제로는 GET일때도 데이터 Locality 에 따라 몇번의 리모트 호출이 발생할 수 있음
opennaru.com | 2013 | All Rights Reserved 47
• Invalidation는 실제로는 데이터를 공유하지 않는 클러스터 모드로 리모트 캐쉬로부터 오래된 데이터를 삭제하는 방법
• 데이터베이스와 같은 영속적인 스토어가 있는 경우에만 적용
• Query Offloading 목적으로 읽기가 많은 데이터베이스에 매번 액세스를 하는 것을 데이터그리드에서 제공
• 데이터가 변경되면, 클러스터내의 다른 캐쉬는 그 데이터가 유효성이 없기 때문에 해당 데이터 삭제
Invalidation Mode
opennaru.com | 2013 | All Rights Reserved 48
opennaru.com | 2013 | All Rights Reserved 49
Eviction (제거)
• Eviction는 메모리가 부족해지지 않도록 메모리에서 엔트리를 삭제하는 과정
• 데이터 손실을 막기 위해서는 CacheStore 에 저장
• Eviction은 전체 클러스터를 대상으로 하지 않고 개별 노드를 대상으로 작업
• Eviction 전략
• NONE - 설정되어있는 Eviction 전략 없음
• FIFO - first-in-first-out (선입 선출) 전략
• LRU - least-recenty-used 전략
• UNORDERED - 무작위 Eviction 전략
• LIRS - Low Inter-reference Recency Set 패턴
• Eviction 선언 예
• 최대 1000 개 엔트리, LRU Eviction 전략, 500 ms 마다 Eviction 쓰레드 실행
<infinispan>
<namedCache name="evictionCache">
<eviction maxEntries="1000“ strategy="LRU” wakeUpInterval="500" />
</namedCache>
</infinispan>
opennaru.com | 2013 | All Rights Reserved 50
Expiration (만료) – 1/2
• Eviction와 Expiration 차이
• Eviction - 엔트리 최대수를 넘었을 경우에 삭제
• Expiration - 엔트리 보관 기간을 넘겼을 경우에 삭제
• Expiration는 지정된 시간을 넘긴 엔트리를 삭제
• 엔트리에 lifespan, maximum idle time을 설정하고 초과하는 엔트리는 제거
• Expiration 엔트리는 Eviction 엔트리와 같이 passivate 되지 않음
• Expiration 엔트리는 글로벌하게 삭제
• 메모리, CacheStore, 클러스터 와이드 모두
• Expiration의 예
• HTTP Session
• SFSB Session
opennaru.com | 2013 | All Rights Reserved 51
Expiration (만료) – 2/2
• evictionCache 라는 이름의 Cache 선언
• 최대 1,000 개 엔트리만 메모리에 저장
• Expiration 쓰레드는 500ms 마다 실행
• 엔트리는 생성된 지 60,000 ms 되거나 사용된지 10,000 ms 가 지나면 둘 중 먼저의 경우에 만료
<infinispan>
<namedCache name="evictionCache">
<eviction maxEntries="1000"
strategy="LRU” />
<expiration
wakeUpInterval="500"
lifespan="60000"
maxIdle="10000” />
<loaders passivation="true">
<loader
class="org.infinispan.loaders.file.FileCacheStore">
<properties>
<property name="location"
value="${java.io.tmpdir}"/>
</properties>
</loader>
</loaders>
</namedCache>
</infinispan>
opennaru.com | 2013 | All Rights Reserved 52
Header text
opennaru.com | 2013 | All Rights Reserved 53
• 캐쉬 엔트리 read/ 캐쉬 엔트리 저장
• 여러가지 종류의 저장 구조 지원
• FileSystem
• FileCacheStrore:개발시 사용/ 단순한 구조
• JDBC
• JdbcBinaryCacheStore:오브젝트 타입 키 지원
• JdbcStringBasedCacheStore:스트링형 키
• JdbcMixedCacheStore:스트링형 키와 오브젝트 타입 키
• S3등 Cloud
• Remote Store
• Cassandra Store
CacheStore
JDG App
Shared Store
JDG App
JDG App
opennaru.com | 2013 | All Rights Reserved 54
CacheStore 설정 - File 기반
• 캐쉬스토어 설정 (File/JDBC)
• 파일 스토어: <file-store>
• JDBC 스토어: <string-keyed-jdbc-store>, <binary-keyed-jdbc-store>, <mixed-keyed-jdbc-store>
• 파일 스토어를 사용하는 경우: 다음과 같이 standalone-ha.xml 를 설정
• file-store에 패스 설정을 생략 했을 경우, standalone/data/디렉토리 아래에 캐쉬의 보존 파일이 작성됩니다.
···
<distributed-cache name=“myCache" mode="SYNC" start="EAGER"/>
<file-store/>
</distributed-cache>
···
standalone-ha.xml 에 myCache 를 정의 한 예 :
opennaru.com | 2013 | All Rights Reserved 55
JDBC CacheStore 설정
• JDBC CacheStore를 설정
<subsystem xmlns="urn:jboss:domain:infinispan:1.3" default-cache-container="clustered">
<cache-container name="clustered" default-cache="default">
:
<distributed-cache name=“myCache" mode="SYNC" start="EAGER">
<locking isolation="READ_COMMITTED" acquire-timeout="30000"
concurrency-level="1000" striping="false" />
<transaction mode="NONE" />
<string-keyed-jdbc-store datasource="java:jboss/datasources/OracleDS"
shared="true"
passivation="false"
preload="false"
purge="false">
<property name="databaseType">oracle</property>
<string-keyed-table prefix="JDG">
<id-column name="id" type="VARCHAR(100)"/>
<data-column name="datum" type="LONG RAW"/>
<timestamp-column name="version" type="NUMBER"/>
</string-keyed-table>
</string-keyed-jdbc-store>
</distributed-cache>
</cache-container>
opennaru.com | 2013 | All Rights Reserved 56
CacheStore 설정 – 비동기 설정
• Client-server 모드로 캐쉬스토어를 비동기로 설정하려면 ,<write-behind>엘리먼트를 사용
<distributed-cache name="DISTCACHE" mode="SYNC" start="EAGER">
<transaction mode="NONE" />
<string-keyed-jdbc-store datasource="java:jboss/datasources/OracleDS”
shared="true”
passivation="false"
preload="false"
purge="false">
<write-behind flush-lock-timeout=“10000”
modification-queue-size=”500"
shutdown-timeout="25000”
thread-pool-size="1"/>
:
※시간에 관한 파라미터는 밀리 세컨드
standalone/configuration/standalone-ha.xml:
opennaru.com | 2013 | All Rights Reserved 57
• CacheStore 저장 방법
• Write-Through (동기 쓰기)
• Write-Behind(비동기 쓰기)
• Write-Through Cache
• 캐쉬와 CacheStore가 동시에 업데이트 되어 데이터 일관성 유지
• 엔트리 변경 시 성능 감소
• Write-Behind Cache
• CacheStore에 대한 업데이트를 비동기로 실행하여, 클라이언트 thread와 CacheStore 업데이트 thread는 별도 쓰레드
• 엔트리 변경 시 CacheStore 반영에 성능 영향도 없음
Write-Through, Write-Behind Cache
opennaru.com | 2013 | All Rights Reserved 58
Header text
opennaru.com | 2013 | All Rights Reserved 59
Sample Code – library Mode
• Cache에 데이터를 저장, 읽기, 삭제
• 기본 정의되어 있는 DefaultCache 를 이용
public static void main(String[] args) {
EmbeddedCacheManager manager = new DefaultCacheManager();
Cache<String, String> cache = manager.getCache(“CacheName”);
cache.put(“key”, “value”);
cache.get(“key”);
cache.remove(“key”);
}
opennaru.com | 2013 | All Rights Reserved 60
Sample Code – Client/Server Mode
• Hot Rod Protocol 을 이용한 원격 클러스터링 환경
• 기본적인 메소드는 Library mode와 동일
public static void main(String[] args) {
RemoteCacheManager manager = new RemoteCacheManager(“192.168. 0.1:11223”);
Cache<String, String> cache = manager.getCache(“CacheName”);
cache.put(“key”, “value”);
cache.get(“key”);
cache.remove(“key”);
}
opennaru.com | 2013 | All Rights Reserved 61
JBoss Datagrid code vs. Coherence Code
NamedCache nc
= CacheFactory.getCache("mine");
cache.put("key", "hello world");
String name = cache.get("key");
System.out.println(“String is "+name);
DefaultCacheManager m
= new DefaultCacheManager();
Cache<String, String> cache = m.getCache();
cache.put("key", "hello world");
String name= cache.get("key");
System.out.println(“String is "+name);
Coherence Example JBoss Datagrid Example
opennaru.com | 2013 | All Rights Reserved 62
Header text
opennaru.com | 2013 | All Rights Reserved 63
Distributed Executor
• 분산 실행 기능
• 데이터가 저장되어 있는 인스턴스에서 실행하여 결과를 반환
• 디스크 액세스나 네트워크 액세스를 줄여 고속 실행
opennaru.com | 2013 | All Rights Reserved 64
Distributed Executor
• 캐쉬에 대해 전체 대상으로 적용
• Callable의 call(), setEnvironment()를 구현
• DistributedExecutorService executor = new DefaultExecutorService(cache);
• DistributedCallable callable = new MyDistributedCallable();
• List results = executor.submitEverywhere(callable);
opennaru.com | 2013 | All Rights Reserved 65
Header text
opennaru.com | 2013 | All Rights Reserved 66
Map/Reduce
• Hadoop 의 분산병렬 처리와 동일
• Map/Reduce
• Job 실행한다
• 데이터를 저장하고 있는 인스턴스에서 Map 실행
• 중간 데이터를 Cache에 저장
• 데이터를 저장하고 있는 인스턴스에서 Reduce 처리
• 결과를 Job에 반환
opennaru.com | 2013 | All Rights Reserved 67
• SUM 결과 취합같은 경우 사용
• Mapper.map, Reducer.reduce 구현
• MapReduceTask task = new MapReduceTask(cache);
• task.mappedWith(new MyMapper()). reducedWith(new MyReducer());
• Map results = task.execute();
Map/Reduce Interface
opennaru.com | 2013 | All Rights Reserved 68
Header text
opennaru.com | 2013 | All Rights Reserved 69
Query API
• 풀텍스트 검색 엔진 Apache Lucene의 Lucene Directory 로 구현
• put시에 데이터 index를 생성/저장
• Hibernate Search API를 사용해 검색
opennaru.com | 2013 | All Rights Reserved 70
Header text
opennaru.com | 2013 | All Rights Reserved 71
User API Map
• API
org.infinispan.cache extends java.concurrent.ConcurrentMap
Cache<Integer, Date> cache = cacheManager.getCache(cacheName);
Date value2 = cache.get(key) | getASync()
cache . put() | putAll() | putASync() | putAllASync()
• Annotations
@CacheResult – use the cache
@CachePut – put into the cache
@CacheRemoveEntry – remove a single entry from the cache
opennaru.com | 2013 | All Rights Reserved 72
•캐쉬 조작을 JTA 트랜잭션(transaction)상에서 사용할 수 있습니다. • MVCC(Multi-Versioned Concurrency Control) • 캐쉬 엔트리 락 • commit/rollback의 지원 • 동일 트랜잭션(transaction)내에서의 복수의 캐시 인스턴스 조작 • 데드락 검출
try { utx.begin(); Integer value = cache1.get(key); // get에서는 분산 락은 취득하지 않는다 cache1.lock(key) // 명시적인 분산 락 취득[1] value = cache1.get(key); value = value + 1; cache1.put(key, value); // 데이터 변경 cache2.put(key, value); // 암묵적인 분산 락의 취득[2], 데이터의 변경 utx.commit(); // 변경의 반영, 분산 락 개방 } catch (Exception e) { utx.rollback(); // 변경의 취소, 분산 락 개방 }
• Distribution 캐쉬의 경우, commit 시 데이터를 복제 합니다.
[1] get에서는 락을 취득하지 않기 때문에, get→put를 배타적으로 하려면, 명시적으로 락을 취득할 필요가 있습니다. [2] put 조작은 락을 취득하기 때문에, 이 조작에서는 암묵적으로 락 취득을 합니다. 암묵적인 락 취득하게 하려면, 캐쉬
설정을<transaction lockingMode="PESSIMISTIC">과 같이 지정해야 합니다.
JTA 트랜잭션 지원
opennaru.com | 2013 | All Rights Reserved 73
•배치 API는, put을 여러 차례 배치로 조작할 때 성능을 향상시키기 위해 사용할 수 있는 API 입니다. •배치 API는 JTA 트랜잭션(transaction)의 지원과 거의 동일한 기능이 되지만, 트랜잭션(transaction)에 참가 할 수 있는 자원이 1개 JDG 캐시 인스턴스로 한정되는 점이 다릅니다.
try { cache.startBatch(); // 배치 트랜잭션 시작 cache.put("k1", "value"); // 분산 락 취득, 데이터의 변경 cache.put("k2", "value"); // 분산 락 취득, 데이터의 변경 cache.put("k3", "value"); // 분산 락 취득, 데이터의 변경 cache.endBatch(true); // 변경의 반영, 분산 락 개방 } catch (Exception e) { cache.endBatch(false); // 변경의 취소, 분산 락 개방 }
배치 API 지원
opennaru.com | 2013 | All Rights Reserved 74
•커스텀 인터셉터는 이용하는 것으로, 캐쉬 조작에 사용자 함수를 추가 할 수 있습니다. •커스텀 인터셉터는, org.infinispan.interceptors.base.CommandInterceptor 추상 클래스를 상속하여, 필요한 메소드를 override 하여 사용합니다.
원하는 메소드를 오버라이드
커스텀 인터셉터 지원
opennaru.com | 2013 | All Rights Reserved 75
•캐쉬 매니저의 내부 동작에 관한 Notification을 받는 Listener클래스를 등록할 수 있다. •로그 출력 이외의 특별히 사용할 곳은 없다.
@Listener
public class MyListener {
@CacheEntryCreated
public void printMessage(CacheEntryCreatedEvent event) {
System.out.println(event.getKey());
}
}
MyListener listener = new MyListener();
cache.addListener(listener);
캐시/매니저 레벨의 Notification & Listener 지원
opennaru.com | 2013 | All Rights Reserved 76
•라이브러리 모드는 애플리케이션에서 API로 이용하는 형태로 사용됩니다. •WAR 애플리케이션이나, EAR 애플리케이션 안에서 이용합니다.
• JDG 6는 JBoss EAP 6와 JBoss EWS 2(Tomcat 7)을 지원합니다. •캐쉬 매니저의 초기화는 애플리케이션에서 초기화 메소드를 호출하여야 합니다. •캐쉬의 설정은, 설정 파일을 이용한 방법과 API를 이용한 방법이 있습니다. 보통 설정 파일을 이용한 방법을 이용합니다.
@PostConstruct void init() { try { manager = new DefaultCacheManager("my-infinispan.xml"); } catch (Exception e) { throw new RuntimeException(e); } cache = manager.getCache("myCache", true). getAdvancedCache(); }
설정 파일을 지정하여 초기화
<infinispan xsi:schemaLocation="urn:infinispan:config:5.1···> <globalJmxStatistics allowDuplicateDomains="true" jmxDomain="myCache"/> <transport clusterName="libJDG"> <properties> <property name="configurationFile" value="my-jgroup-udp.xml" /> </properties> </transport> </global>
<namedCache name="myCache"> <jmxStatistics enabled="true" /> <clustering mode="distribution"> <sync /> <hash numOwners="2"/> </clustering> </namedCache> </infinispan>
라이브러리 모드 이용 방법
opennaru.com | 2013 | All Rights Reserved 77
Header text
opennaru.com | 2013 | All Rights Reserved 78
Radar Gun 성능 측정 결과
READ : Without tx overhead WRITE : Without tx overhead
Coherence 3 vs Infinispan 5.2 : 2 node ~ 4 node 증가하며 READ / WRITE 테스트
https://github.com/radargun/radargun/wiki
opennaru.com | 2013 | All Rights Reserved 79
Header text
opennaru.com | 2013 | All Rights Reserved 80
Azul Zing JVM
With Zing, Azul delivers:
• No more “Stop The World” in JVM
• Blazing Performance, all the time ─ Machine scale to human scale
• Consistency of Execution, improving service quality ─ Eliminates Java-induced glitches, pauses and stalls
─ Continuously delivers, even when demand spikes
• Java Technology that Unlocks Innovation( -Xmx40g ) ─ Driving incremental revenue and profitability
─ Enabling new capabilities, new offerings, new lines of business
─ Accelerate time to market and gain competitive advantage
• Operational and Capital efficiency and leverage ─ Gain more revenue from existing infrastructure
─ Scale efficiently, up or out -- reduce server sprawl
─ Now your team can focus on new features instead of tuning
─ Stop tuning, get back to creating value
opennaru.com | 2013 | All Rights Reserved 81
Azul Zing vs Oracle JVM GC 시간 비교
Infinispan(JBoss Data Grid) 사용 JVM간의 GC 시간 비교
opennaru.com | 2013 | All Rights Reserved 82
Header text
opennaru.com | 2013 | All Rights Reserved 83
Header text
opennaru.com | 2013 | All Rights Reserved 84
Header text
opennaru.com | 2013 | All Rights Reserved 85
Header text
opennaru.com | 2013 | All Rights Reserved 86
Header text
opennaru.com | 2013 | All Rights Reserved 87
Linked List형태의 Queue 구조
QUEUE_TAIL UUID3
QUEUE_HEAD UUID1
QUEUE_SIZE Integer
InfinispanQueueElement
Object UUID3(nextId) UUID2
InfinispanQueueElement
Object UUID2(nextId) UUID1
1 2
Queue offer
Queue offer 1) 캐시에서 QUEUE_TAIL의 Value를 가져온다. 2) QUEUE_TAIL의 값이 새로 추가할 KEY 값이다. 3) 새로운 Queue Element에 다음에 추가될 Element에 대한 Key를 UUID 로 미리 생성한다. 4) 생성한 Key는 Element의 nextId에 보관하여 저장한다. 5) nextId를 QUEUE_TAIL에 저장한다.
K V
K V K V Queue poll
Queue poll 1) 캐시에서 QUEUE_HEAD의 Value를 가져온다. 2) QUEUE_HEAD의 값 UUID가 꺼낼 Queue의 KEY 값이다. 3) GET한 Element의 nextID를 QUEUE_HEAD에 보관한다.
https://github.com/nameislocus/infinispan-queue
http://opennaru.blog.me/30185915829
opennaru.com | 2013 | All Rights Reserved 88
Header text
opennaru.com | 2013 | All Rights Reserved 89
KHAN Provisioning 은?
OS 만 설치되어 있으면
수분 이내에 설치 환경
을 테스트하고 웹서버
와 WAS서버를 설치하
고 즉시 서비스할 수 있
는 환경 제공
미들웨어 전문가가 아니
어도 전문가 수준의 시
스템 튜닝이나 난이도
높은 구성을 할 수 있도
록 기능 제공
서버 구성에 대한 정보
만 입력하면 한대에서
수 십대까지 규모에 상
관없이 자동으로
웹시스템 운영환경을
구성
웹시스템 설치/구성
보고서를 시스템에 맞
게 자동으로 생성하여
개발팀과 운영 팀에게
제공
수 분 내 튜닝된 웹 서버와 WAS 서버로 웹 시스템 구축
opennaru.com | 2013 | All Rights Reserved 90
KHAN [provisioning] 웹 기반 GUI
opennaru.com | 2013 | All Rights Reserved 91
Header text
opennaru.com | 2013 | All Rights Reserved 92
Header text