JCF3.0™ Rule Engine Guide(ver3.1)

From JCFWiKi

Jump to: navigation, search

그림:check.gif

  • 산출물 : JCF3.0™ Rule Engine 가이드
  • 작성자: 고경철
  • 작성일 : 2008/02/14
  • 버전 : 1.0
  • 개정이력 :

Copyright © 2008 Daewoo Information Systems Co., Ltd.

목차

[편집] 룰엔진이란?

[편집] 비즈니스 룰이란?

  • 업무의 절차, 흐름, 규칙
  • 비즈니스 룰은 모든 비즈니스 구조 또는 프로세스 내의 암묵적, 명시적 지식을 제공한다.
  • 기존의 비즈니스 룰의 구조
  • IF-THAN 구조
IF
	기혼자이다.
AND
	자녀 수가 3명 이상이다.
THEN
	가족수당을 10% 추가 지급한다.
    • 일반적으로 하드 코딩 형태로 구현

[편집] Business Rule Engine

  • 룰엔진은 룰을 정의하고 실행할 수 있는 환경과 함께 프로그램에서 룰을 호출할 수 있는 인터페이스를 제공
  • Rule을 외부화
    • 코드와 Rule의 분리
    • 비즈니스 로직의 데이터화
전형적인 프로그래밍 접근-Rule이 소스와 혼재되어 있음,개발자만이 수정할 수 있음.
전형적인 프로그래밍 접근-Rule이 소스와 혼재되어 있음,개발자만이 수정할 수 있음.
비지니스 룰엔진 기반 접근-Rule이 독립적으로 분리됨 (룰의 컴포넌트화),비즈니스 분석가 및 현업에서 운영 및 보수 할 수 있음
비지니스 룰엔진 기반 접근-Rule이 독립적으로 분리됨 (룰의 컴포넌트화),비즈니스 분석가 및 현업에서 운영 및 보수 할 수 있음

[편집] Rule Engine이 왜 필요한가? - 전형적인 프로그래밍 접근

  • 문제점
    • Rule이 각 시스템 혹은 소스에 중복되어 혼재
    • Rule을 코드와 분리하기 어려움
    • Rule 자체의 syntex를 실무자가 이해해기 어려움
    • 변경/테스트의 어려움
    • 중복된 개발/유지 보수 비용

[편집] Rule Engine이 왜 필요한가? - 비지니스 룰엔진 기반 접근

  • 장점
    • Rule의 공유와 재사용
    • 신속한 변경 및 테스트(Time to Market / Business Agility)
    • 개발/유지 보수비용의 절감

[편집] drools 룰엔진 소개

[편집] Jboss Rules 개요

  • 비즈니스 정책에 대한 접근, 변경, 관리를 쉽게 만들어주는 표준 기반의 오픈 소스 비즈니스 룰 엔진을 제공
  • 높은 효율성을 갖는 고속의 비즈니스 룰 엔진
  • 비즈니스 분석가나 비즈니스 감사자들이 비즈니스 룰들을 한눈에 살펴보고, 해당 규칙을 IT 환경에 맞추어 인코딩할 수 있도록 도와줌
  • 다양한 언어와 의사 결정테이블 입력 방식을 지원 비즈니스 정책들을 빠르게 변경하여 비즈니스 기회에 빠르게 대처할 수 있도록 도와줌

[편집] JBoss Rules 기능 요약

  • 오픈 소스
    • JBoss Rules는 아파치 소프트웨어 재단의 오픈 소스 라이센스를 채택
    • 제품을 자유롭게 다운로드하여 사용하거나 재 배포할 수 있음
  • 어플리케이션 단순화와 변화에의 빠른 대처
    • JBoss Rules 엔진은 어플리케이션의 비즈니스 정책이나 규칙 로직을 프로세스, 인프라, 그리고 표현 로직으로부터 분리.
  • 효율성과 확장성
    • JBoss Rules는 복잡한 의사 결정 로직을 수집
    • 수집한 의사 결정 로직을 사람이 직접 다루기 힘들정도로 거대한 데이터 집합 상에서도 효과적으로 동작하도록 도와줌.
  • 지식 기반(Knowledge base) 이전
    • JBoss Rules 엔진은 중앙 집중화된 저장소로 기업의 지식 기반을 쉽게 이전할 수 있도록 도와줌.
    • 핵심 의사 결정자나, 관리자들이 없는 경우에도 비즈니스 규칙에 기반하여 업무가 처리될 수 있도록 도와줌.
  • 서비스 지향 아키텍쳐나 어플리케이션상에서 비즈니스 규칙의 재사용
    • JBoss Rules를 사용하여 비즈니스 규칙을 다른 로직으로부터 분리하게 되면, 서비스 지향적인 아키텍쳐 환경이나 기타 어플리케이션에서 해당 비즈니스 규칙을 쉽게 재사용 할 수 있음
Eclipse IDE
Eclipse IDE

[편집] JBoss Rules Features

  • 어플리케이션에 임베드해서 사용가능
    • J2EE, Servlet/JSP, JSF, Web Services, jBPM, Seam
    • 코어라이브러리1M
  • JSR-94 표준호환
  • Java POJO 오브젝트모델사용
  • Hibernate, EJB3 Java Persistence API 연동
  • Engine
    • RETE / Sequential RETE 구현
    • 동적인 룰 추가/제거
    • 교체 가능한 룰언어(Java/MVEL)
    • Stateful /Stateless 실행모드
    • 비동기 실행지원
  • 룰 저작
    • DRL, XML 포맷지원
    • 템플릿기반의DSL 지원
    • Decision Table (Excel, Open Office), GoogleDocs
  • 필드연산자
    • ==, !=, <, <=, >, >=, matches, not matches, contains, not contains, in, not in, memberOf, not memberOf
  • 조건
    • And, Or, Exists, Not, Accumulate, Collect, From , Forall
  • 실행제어
    • 교체 가능한 Conflict Resolution (salience)
    • Agenda Filter
    • Agenda Group
    • Activation Group
    • Rule Flow
    • Attributes (no-loop, lock-on-active)
  • BRMS
    • 웹 기반의 룰 에디터
    • 룰/패키지별 컨트롤
    • 카테고리에 따른 룰 분류
    • 룰빌드 및 디플로이
    • Oracle, MySQL, MS SQL Server 지원

[편집] Drools 룰엔진 성능 및 사례

그림:warning.gif

Drools룰엔진과 JRules룰엔진의 비교 아티클 : http://blog.athico.com/2007/08/drools-vs-jrules-performance-and-future.html

  • 성능 저하 거의 없음
  • 여타 룰엔진 보다 기본적으로 3~4배 이상 빠른 처리능력

그림:warning.gif

Drools Success Stories : http://blog.athico.com/2008/01/drools-success-stories-seattle-code.html

  • "We are using Drools VERY successfuly around 3 years (We started with version 2.x). And it has being so usefull that now we have a very big system running on more than one customer in telecom market.
  • Currently we do have a server running around 300 rules, where we assert millions of facts at once. The objective is to guide and rate telecom usage events. We are able to apply those 300 rules over 20 Milion facts and get results (Guided and Rated) around 1 hour( Note: First we have to read many binary files, perform a charset conversion on data, load it in our object model, assert objects in working memory, apply around 200 rules to enrich the data, assert again in a new working memory, and rate the events accessing external RDBMS databases - caching results of course)."
  • "We tested several deployment and architecture variants (esp. for batch processing), with <100 and <10 facts for each data-row within our batches, but a few million rows. Worked out fine.
  • "We deployed a Drools based solution to a client in the pharmaceutical distribution world (Fortune 100 company :-). We used Drools to power the decisions an interactive voice ordering system. A small number of rules initially but growing constantly
룰 스크립트 패턴
룰 스크립트 패턴

[편집] 비즈니스 룰 도출 및 다양한 룰 작성 방법소개

[편집] 비즈니스 룰 도출

  • 룰이 무엇인가?
    • 업무의 절차, 흐름, 규칙
    • 재사용이 가능하고, 빈번히 변경되며, 공개된 표준규칙이어서 자산이 될 수 있어야 함.
    • 논리적, 직관적
    • 프로세스와는 독립적으로 재사용 가능, ex)표준 산식, 국세청 2007년 연말정산 산식

[편집] Rule Script 작성방법

  • 목표 및 기능
    • 룰 flow에 작성된 RuleFlowGroup의 세부 룰 로직을 룰 Script로 작성한다.
    • IF-Then 문법 보다 간단한 룰 syntex 제공
    • 다양한 룰 요구사항에 최적화 된 문법
  • 구조
    • Rule Attributes
    • Left Hand Side (when) Conditional Elements
    • The Right Hand Side (then)
rule "<name>"
<attribute>*
when
<conditional element>*
then
<action>* end
  • 예제 룰 분석
rule "Approve if not rejected"
salience -100 agenda-group "approval"
when
not Rejection()

p : Policy(approved == false, policyState:status) exists Driver(age > 25) Process(status == policyState)

then
log("APPROVED: due to no objections.");

p.setApproved(true);

end

[편집] Rule language 문법

[편집] 주요 Rule Attributes

그림:check.gif

Rule Attributes 메뉴얼 :http://downloads.jboss.com/drools/docs/4.0.4.17825.GA/html_single/index.html#d0e2965

[편집] Left Hand Side (when) Conditional Elements

그림:check.gif

Left Hand Side (when) Conditional Elements 메뉴얼 :http://downloads.jboss.com/drools/docs/4.0.4.17825.GA/html_single/index.html#RuleLanguage-ConditionalElements

[편집] The Right Hand Side (then)

그림:check.gif

The Right Hand Side 메뉴얼 :http://downloads.jboss.com/drools/docs/4.0.4.17825.GA/html_single/index.html#d0e4123

  • DB 및 Legacy 코드 재사용가능
    • 예제
rule "point"
	salience 85
//	 dialect "mvel"
	when		
		e : Employee (point >=1 , point <=4, level<=3)
	then
		 if (e.getPoint() == 1){		  
	     	 e.setBasicpay(e.getBasicpay() + 500);
	     	 System.out.println(e.getName() +":"+ "보너스(평가 A)" + e.getBasicpay());    	 
	     	 String log ="보너스(평가 A)" + e.getBasicpay();
			 e.message.add(log);  
	     	 }
	     else if 
	     	(e.getPoint() == 2){		  
	     	 e.setBasicpay(e.getBasicpay() + 400);
	     	 System.out.println(e.getName() +":"+ "보너스(평가 B)" + e.getBasicpay());
	     	 String log ="보너스(평가 B)" + e.getBasicpay();
			 e.message.add(log);  
	     	 }	     	 
	     else if 
	     	(e.getPoint() == 3){		  
	     	 e.setBasicpay(e.getBasicpay() + 300);
	     	 System.out.println(e.getName() +":"+ "보너스(평가 C)" + e.getBasicpay());
	     	 String log ="보너스(평가 C)" + e.getBasicpay();
			 e.message.add(log);  
	     	 }
	     else if 
	     	(e.getPoint() == 4){		  
	     	 e.setBasicpay(e.getBasicpay() + 200);
	     	 System.out.println(e.getName() +":"+ "보너스(평가 D)" + e.getBasicpay());
	     	 String log ="보너스(평가 D)" + e.getBasicpay();
			 e.message.add(log);  
	     	 }  
end

[편집] Rule language 작성 예제

그림:forbidden.gif

  • Question #1
    • Rule : 직책이 팀장인 직원은 팀 성과가 B 이상일 경우만 직원의 개인평가에 따른 보너스 수당을 적용하기로 한다.
    • Fact :
      1. Employee
      2. Team
  • 정답
rule "팀장보너스"
	salience 90
	when		
		e : Employee (level=="팀장")
                t : Team(point =="B",point =="A" )		
	then
		 e.setBasicpay(e.getBasicpay() + 10);		
		 System.out.println(e.getName() +":"+ "팀장 보너스" + e.getBasicpay());
		 String log ="팀장 보너스" + e.getBasicpay();
		 e.message.add(log);  	 		
end

[편집] Rule flow 작성방법

이클립스 플러그인을 이용한 룰플로우 작성모습
이클립스 플러그인을 이용한 룰플로우 작성모습

그림:check.gif

룰플로우 작성 메뉴얼:http://downloads.jboss.com/drools/docs/4.0.4.17825.GA/html_single/index.html#d0e4357

  • 적용 Project에서 쓰일 Process를 기술
  • Drools 이클립스 플러그인 사용
  • 업무 전문가가 쉽게 이해할 수 있음.
  • 업무 프로세스 변동 시 빠르게 유지보수가 가능함.
룰과 룰 플로우의 관계
룰과 룰 플로우의 관계
dsl편집
dsl편집
dsl의 활용
dsl의 활용

[편집] DSL Syntax 작성방법

  • 룰 스크립트 작성시 유지보수를 쉽게 해줌.
  • 엑셀 및 open office로도 룰 작성 가능
    • 룰 작성 및 운영의 주체를 개발자에서 현업으로 shift

[편집] 룰엔진 구동원리

룰엔진구동원리
룰엔진구동원리

[편집] fact 와 Rule

  • fact
    • 룰에 적용될 오브젝트
    • 워킹메모리 안으로 추가되는 어플리케이션의 객체
    • 룰 세션에 따라 하나의 오브젝트 또는 여러개의 오브젝트가 들어갈 수 있음
  • rule
    • 룰 파일(drl)에서 만들어진 룰들
    • Agenda-Group를 통해 룰들이 관계지어짐

[편집] RuleSession

  • Stateful Session
    • 룰세션이 유지되면, 여러 부분에서 룰을 적용할 경우 룰을 적용할 대상 오브젝트를 추가해주기만 하면 됨.
    • 한 어플리케이션에서 여러 개의 비즈니스 로직이 룰엔진을 사용할 경우 룰세션이 유지되는 stateful방식을 사용하는 것이 유리함
final StatefulSession session = ruleBase.newStatefulSession();
session.insert(employee);  //만들어진 룰세션에 오브젝트를 삽입
session.retract(stiltonHandel);  //룰세션에서 기존 오브젝트를 삭제
session.update(stiltonHandle,stilton); // 룰세션에서 기존 오브젝트를 업데이트
  • Stateless Session
    • 룰세션을 유지하지 않은 상태.
    • Stateless Session으로 룰엔진을 구동할 경우는 세션이 없으므로 다른 부분에 룰엔진을 적용한 것과 독립적으로 구동 됨.
final StatelessSession session = ruleBase.newStatelessSession();
session.execute(employee);     //룰세션에 오브젝트를 넣어서 실행

[편집] example

// (1) create RuleBase
RuleAgent agent = RuleAgent.newRuleAgent(“brmsdeployedrules.properrties);
RuleBase ruleBase = agent.getRuleBase();
// (2) build a WorkingMemory from the rule base
StatefulSession session = ruleBase.newStatefulSession();
session.startProcess(“insuranceProcess”);
// (3) assert facts
session.insert(driver);
session.insert(car);
session.insert(policy);
// (4) fire rules
session.fireAllRules( );
session.dispose();

[편집] 룰엔진개발환경

[편집] drools IDE 설치

그림:warning.gif

가이드 참조 :http://downloads.jboss.com/drools/docs/4.0.4.17825.GA/html_single/index.html#d0e1288

[편집] 라이브러리

  • drools-core.jar
  • drools-compiler.jar
  • drools-jsr94.jar
  • drools-decisiontables.jar

[편집] 디버깅

  • You can debug rules during the execution of your Drools application
  • Drools breakpoints are only enabled if you debug your application as a Drools Application
  • Select the "Debug As >" and select Drools Application

[편집] Documents

그림:warning.gif

가이드 참조 :http://labs.jboss.com/drools/documentation.html

[편집] JCF 프레임워크와 룰엔진의 연동

[편집] 개요

  • 개요
    • 그림참조
JCf ruleEngine Service Tier
JCf ruleEngine Service Tier
  • 개발주체
    • 룰파일 및 agendaGroup =>비즈니스 룰개발자
    • service파일 => 일반 어플리케이션 개발자

[편집] JCF 룰엔진 서비스 Tier

  • 룰 작성기준
    • Rule File
      • 재사용이 가능하는가에 대한 기준을 가지고 룰을 작성한다.
      • 몇개의 룰이 트렌젝션으로 쓰일 수 있는 관계가 있다면 agendaGroup으로 묶는다.
      • 룰안에 When 부분에서 룰이 활성화되는 조건을 설정할 수 있지만 어플리케이션에 종속되지 않는 조건을 넣도록 해야된다.(재사용성)
      • when 부분에 넣는것들 룰자체의 표준적인 factor를 사용,모델의 값을 넣치 않는다.
      • 모델의 값을 조건으로 넣는 경우는 service에서 처리한다.
    • AgendaGroupDelegate
      • 룰 파일 혹은 룰 플로우 파일등을 부른다.
      • 룰 세션을 생성한다.
      • 비즈니스로직에 따라 agendaGroup들을 메소드로 묶는다.
      • 예제
//직원
    public void employee() {
        this.session.setFocus( "point" );
        this.session.setFocus("level");
        this.session.setFocus("year");
        this.session.fireAllRules();     
    }
    • Service
      • Fact를 룰 세션에 주입한다.
      • Fact의 값에 따라 AgendaGroupDelegate에서 생성된 메소드를 부를지를 결정한다.
      • 개발자는 굳히 어떠한 룰이 있고 그 룰이 어떤 다른 룰과 트렌젝션 관계가 있는지 몰라도 된다.
      • 예제
   if (employee.getLevel() != 4) {          // 직원에 관한 룰 적용
	    	 this.delegate.employee();
	    }else if (employee.getLevel() ==4){   //임원에 관한 룰 적용
	    	  this.delegate.employee(); 
	    	  this.delegate.allEmployee(); 
	    }

[편집] JCF 룰엔진 통합예제

그림:forbidden.gif

  • 급여 부분의 수당로직을 몇가지 뽑아냄

[편집] model

  • 이름, 기본급, 근속년수, 결혼유무, 자녀수, 직급, 평가

[편집] Rule

  • 근속년수에 따른 근속 수당을 매월 지급
    • 근속년수 1~5년 : 근속년수 * 5000원 - 1000원
    • 근속년수 6~10년 : 근속년수 * 6000원 - 2000원
    • 근속년수 11~15년 : 근속년수 * 7000원 - 3000원
    • 근속년수 16~20년 : 근속년수 * 8000원 - 5000원
    • 근속년수 21년 : 정액 170,000원
  • 가족수당(결혼 유무 , 자녀수)
    • 배우자 10,000원 자녀1명당 5,000 최대 자녀 3명까지
    • 배우자 없는데 자녀 있는경우 자녀 1명당 10,000 최대 자녀 3명까지
  • 직급수당
    • 대리 20,000
    • 과장 30,000
    • 차장 40,000
    • 부장 50,000
  • 평가에 따른 보너스 지급
    • 평가 A : 500,000
    • 평가 B : 400,000
    • 평가 C : 300,000
    • 평가 D : 200,000
    • 직급 차장 이하만 보너스 지급 (부장은 지급 안함)

[편집] Service

  • 룰 처리 방식에 따라 분기 가능
  • 예제
    • 어플리케이션안에 AgendaGroup과 ruleflow방식이 혼재할 경우
    if ( executionControl == AbstractRunConway.RULEFLOWGROUP ) {
            delegate = new RuleFlowDelegate();
        } else {
            delegate = new AgendaGroupDelegate();
        }
  • AgendaGroupDelegate
	public Employee findEmployee(int employeeId ) throws Exception {
		final Employee employee = employeeDao.findEmployee(employeeId);	
		employee.message = new ArrayList();  
				delegate = new AgendaGroupDelegate();
		this.session=delegate.getSession();
		
	    this.session.insert(employee);		//fact 주입
	  
	    if (employee.getLevel() != 4) {          // 직원에 관한 룰 적용
	    	 this.delegate.employee();
	    }else if (employee.getLevel() ==4){   //임원에 관한 룰 적용
	    	  this.delegate.employee(); 
	    	  this.delegate.allEmployee(); 
	    }	   
	    session.dispose();
		return employee;	
			}
  • RuleFlowDelegate
public RuleFlowDelegate() {
        final Reader drl = new InputStreamReader( CellGridImpl.class.getResourceAsStream( "/org/drools/examples/conway/conway-ruleflow.drl" ) );
        final Reader calculateRf = new InputStreamReader( CellGridImpl.class.getResourceAsStream( "/org/drools/examples/conway/calculate.rfm" ) );
        final Reader generationRf = new InputStreamReader( CellGridImpl.class.getResourceAsStream( "/org/drools/examples/conway/generation.rfm" ) );
        final Reader killAllRf = new InputStreamReader( CellGridImpl.class.getResourceAsStream( "/org/drools/examples/conway/killAll.rfm" ) );
        final Reader registerNeighborRf = new InputStreamReader( CellGridImpl.class.getResourceAsStream( "/org/drools/examples/conway/registerNeighbor.rfm" ) );
 
        try {
            PackageBuilder builder = new PackageBuilder();
            builder.addPackageFromDrl( drl );
            builder.addRuleFlow( calculateRf );
            builder.addRuleFlow( generationRf );
            builder.addRuleFlow( killAllRf );
            builder.addRuleFlow( registerNeighborRf );
 
            RuleBase ruleBase = RuleBaseFactory.newRuleBase();
            ruleBase.addPackage( builder.getPackage() );
 
            this.session = ruleBase.newStatefulSession();
 
        } catch ( Exception e ) {
            throw new RuntimeException( e );
        }
    }

[편집] Deligate

  • 룰파일을 부르고 룰세션설정을 하는등 룰엔진 활성화에 관련된 부분을 담당
  • 일반적인 룰파일을 적용되는 비즈니스로직에 맞게 management
public class AgendaGroupDelegate implements RuleDelegate {
    private StatefulSession session;    
    public AgendaGroupDelegate() {
        final Reader drl = new InputStreamReader( AgendaGroupDelegate.class.getResourceAsStream( "payScript.drl" ) );
        try {
            PackageBuilder builder = new PackageBuilder();
            builder.addPackageFromDrl( drl );
 
            RuleBase ruleBase = RuleBaseFactory.newRuleBase();
            ruleBase.addPackage( builder.getPackage() );
 
            this.session = ruleBase.newStatefulSession();
 
        } catch ( Exception e ) {
            throw new RuntimeException( e );
        }
    }
    public StatefulSession getSession() {
        return this.session;
    }    
//직원
    public void employee() {
        this.session.setFocus( "point" );
        this.session.setFocus("level");
        this.session.setFocus("year");
        this.session.fireAllRules();     
    }
//임직원 
    public void allEmployee() {
        // System.out.println( "next generation" );
        session.setFocus( "Marry" );
        session.setFocus( "family" );       
        session.fireAllRules();       
    }

[편집] RuleFile

그림:check.gif

룰 요구사항을 룰 script로 작성: http://wiki.dev.daewoobrenic.co.kr/mediawiki/index.php/JCF3.0%E2%84%A2_Rule_Engine_Guide_-_rule_language#xml.EB.A1.9C_.EA.B5.AC.ED.98.84.EB.90.9C_.EB.A3.B0

[편집] BRMS:룰의 자산화

Drools 룰엔진은 웹을 통해 룰을 작성하고 관리하며 공유, 및 배포가 가능한 웹 시스템을 제공
Drools 룰엔진은 웹을 통해 룰을 작성하고 관리하며 공유, 및 배포가 가능한 웹 시스템을 제공
  • Business Rule Management System
    • Drools에서 독립적인 룰 관리 툴 제공
    • Web 환경으로 룰 파일 작성 가능
    • 현업 업무전문가가 접근성 보장
    • 룰 파일을 조회 및 다운로드 할 수 있음
    • 전사적으로 공통 룰을 통합 관리하면 룰의 Reuse가 가능하다.
  • 향후 계획
    • Drools BRMS를 통해 표준 룰로직을 Rule File로 만들고 통합 관리하는 BRMS 설치하여 지원

[편집] 참고자료 및 발표자료