狠狠撸

狠狠撸Share a Scribd company logo
如何建立企業級應用的
商業規則引擎
李日貴 Jini Gary Lee
王文農 Steven Wang
為何要使用规则引擎
Java Multi-tiers
? Struts
? JSF
? SpringMVC
? Tapestry
? Wicket
MVC
Front Tier
DAO
Persistence Tier
Buisiness Logic
Middle Tier
? Hibernate
? MyBatis
? JDO
? JPA
RuleEngine 的好處
? 宣告式的開發
? 區隔商業邏輯與資料處理的程式
? 效能與擴充性
? 集中控管商業邏輯
? 簡易的工具
? 可閱讀的規則
Rule ?
When
(Conditions)
THEN
(Actions)
Rule Engine
Working
Memory
Production
Memory
Match Rules
Resolve
Conflicts
(Agenda)
Fire RulesFact Rules
Forward Chaining
Rule
Base
Working
Memory
Determine possible
rules to fire
Select
Rules
to Fire
Conflict
Resolution
Strtegy
Exit
Fire Rule
Conflict Set
Rule Found
No Rule Found
Exit if specified by rule
Rete
? Dr. Charles L. Forgy , 1974
? Data struture
– List of elements
– Tree-Strutured Sorting Network
? Algorithm
– Rule Compilation
– Runtime Execution
http://en.wikipedia.org/wiki/File:Rete.svg
JSR-94
? Java Rule Engine API
? JSR94 provides
– Rule Administration
– Rule Runtime APIs
– Rule Language (RuleML)
JSR94 APIs
? Register and unregister rules
? Parse Rules
? Inspect rule metadata
? Execute Rules
? Retrieve Results
? Filter Results
Rule Engines
? Commercial
– Oracle Business Rules
– IBM iLOG
– Pega Rules
– FICO Blaze Advisor
– JESS ( JSR94 RI )
? Opensources
– JBOSS Drools
– OpenRules
JESS
JESS
? A Rule Engine
? A scripting environment in Java
JESS ?? Java
? Rete algorithm
? LISP-like syntax
? Can be licensed for commercial use, no
cost for academic use
JESS language
? *.clp ( in JessDE )
Basic Syntax
? (a b c) – List of tokens
? (1 2 3) – List of Integers
? (+ 1 2) – Expression
? (“Hello world”) – String
? (foo ?x ?y) – Function
Define Functions
(deffunction max(?a ?b)
(if(> ?a ?b) then
(return ?a)
else
(return ?b)))
(printout t (max 3 5))
Define Advices
(defadvice before + (bind $?argv ( create$
$?argv 1 )))
(printout t (+ 2 3) crlf)
(undefadvice +)
(printout t (+2 3) crlf)
Define Template
(deftemplate automobile
"A specific car."
(slot make)
(slot model)
(slot year (type INTEGER))
(slot color (default white)))
(assert (automobile (model CAMERY) (make TOYOTA) (year 2008)))
(assert (automobile (model 520i) (make BMW) (year 2013)))
(facts)
Define class
(import domain.Account)
(deftemplate Account (declare (from-class Account)))
(bind ?a (new Account))
(add ?a)
(facts)
(modify 0 (id 1) (name jini))
(facts)
(bind ?a (new Account))
(add ?a)
(?a setId 2) (?a setName steven)
(printout t (?a getId) "-" (?a getName) "." crlf)
(facts)
(update ?a)
(facts)
Define rule
(deftemplate person (slot name) (slot age))
(defrule vote "Can you vote"
(person {age < 18})
=>
(printout t "No, you can't vote" crlf)
)
(assert (person (age 17)))
(run)
Use Java
(bind ?map (new java.util.HashMap))
(call ?map put "A" "Apple")
(call ?map put "B" "Banana")
(call ?map put "C" "Cherry")
(printout t (call ?map get "B"))
JessML
<?xml version=‘1.0’ encoding=‘UTF-8’?>
<rulebase xmlns=‘http://www.jessrules.com/JessML/1.0’>
<template>
<name>person</name><slot>name</slot>
<value type=‘SYMBOL’>nil</value>
</template>
<facts>
<name>course</name>
<fact>
<name>id</name><value type=‘INTEGER’>1</value>
</fact>
</facts>
<rule>
<lhs>..</lhs>
<rhs>..</rhs>
</rule>
</rulebase>
JSR 94
public class JessRule {
private static final String RULE_SERVICE_PROVIDER
=“org.jcp.jsr94.jess”;
public void run(){
Class.forName(“org.jcp.jsr94.jess.RuleServiceProviderImpl”);
RuleServiceProvider serviceProvider =
RuleServiceProviderManager
.getRuleRuleServiceProvider(RULE_SERVICE_PROVIDER );
}
}
Drools
Setup RuleIDE
Start Drools Project
simple Rule
package javatwo.license
rule “Check age < 18”
when
$a : Applicant(age < 18)
then
$a.setValid(false);
end
Execute DRL
KnowledgeBuilder kbuilder =
KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("javatwo/
license/licenseApplication.drl"), ResourceType.DRL );
KnowledgeBase kbase =
KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackage
s());
StatelessKnowledgeSession ksession =
kbase.newStatelessKnowledgeSession();
Applicant applicant = new Applicant(1, "Kevin", 15);
ksession.execute(applicant);
Nature Language
kbuilder.add(ResourceFactory.newClassPathResource("nature.dsl"),
ResourceType.DSL );
kbuilder.add(ResourceFactory.newClassPathResource("nature.dslr"),
ResourceType.DSLR );
nature.dsl
[condition][]Person is {name}=$person : Person(name=='{name}')
[consequence][]SayHello=System.out.println("Hello "+$person.getName());
nature.dslr
expander nature.dsl
rule "Nature language"
when
Person is gary
then
SayHello
end
Chinese ?!
cnature.dsl
[condition][]姓名是 {name}=$person : Person(name=='{name}')
[consequence][]打招呼=System.out.println("Hello
"+$person.getName());
cnature.dslr
expander cnature.dsl
rule "Nature language"
when
姓名是 gary
then
打招呼
end
JSR 94
public class DroolsRule {
private static final String RULE_SERVICE_PROVIDER
=“http://drools.org/”;
public void run(){
Class.forName(“org.drools.jsr94.rules.RuleServiceProviderImpl
”);
RuleServiceProvider serviceProvider =
RuleServiceProviderManager
.getRuleRuleServiceProvider(RULE_SERVICE_PROVIDER );
}
}
Script
JSR-223 support
? JSR-223
– javax.script
? The scripting API consists of interfaces and
classes that define Java Scripting Engines and
provides a framework for their use in Java
applications.
– since Java 1.6
? Before JSR-223
– Use BeanShell or etc..
– API not standard
JSR-223 support
Scripting API component
relationships
Eval Script
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a Javascript engine
ScriptEngine engine = factory.getEngineByName(“JavaScript”);
// evaluate Javascript code from String
engine.eval(“print(‘Hello world’)”);
Eval File
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a Javascript engine
ScriptEngine engine = factory.getEngineByName(“JavaScript”);
// evaluate Javascript code from given file – specified by first argument
engine.eval( new java.io.FileReader(args[0]));
Eval Variable
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName(“JavaScript”);
File f = new File(“test.txt”);
// expose File object as variable to script
engine.put(“file”,f);
// evaluate a script string. The script accesses “file” variable and calls
method on it
engine.eval(“print(file.getAbsolutePath())”);
Eval Script Function
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName(“JavaScript”);
// Javascript code in a String
String script = “function hello(name) { print(‘Hello’+name); }”;
engine.eval(script);
// javax.script.Invocable is an optional interface. Check whether your
script engine implements or not! Note that the Javascript engine
implements Invocable interface.
Invocable inv = (Invocable) engine;
inv.invokeFunction(“hello”, “Scripting!!”);
Drools
JESS
But their language/spec…
We want..
We are..
Case 1保費計算
? 不同險種會有不同的保費計算方式,公式
和因子也可能會不相同
? 複雜計算方式需要特殊的方式,最好能夠
在不須知道太多的情況下,Plug-In進來
條件 公式 因子
因
子
公
式
畫
面
D
B
其
他
公式:A+B/C-D
因子 A:畫面
B:Database
C:另一個公式X+Y
D:其他系統
X:常數
Y:Database
PlugIn
保费公式设定
模擬保费公式设定
Case 2核保檢核
? 報價轉保單時,有許多企業邏輯需要被檢
核
? 这些逻辑,我们不希望丑补谤诲肠辞诲别在程式内
條件
規則 結果
規則 結果
規則 結果
.
.
.
1.單一結果或多組結果
2.根據結果進行後續處理
- DataBase操作
-Java操作
-畫面相關操作
PlugIn
Java
Script
SQL
.
.
.
核保检核设定
模擬核保检核设定
测试案例:保单内容
Rule & Engine
Find Match Rules
计算保费处理
核保检核处理
Execute
缺點
1. 不是使用宣告的方法,而是定義處理過程
2. 複雜的業務邏輯,可能會需要巢狀條件結
構,這會使得Rule難以閱讀且容易出錯
3. 可能需要定義代碼處理決定表,或建立更
好的Rule Engine
4. Multiple Script Language將會難以維護
優點
1. 對開發者來說較直接
2. 物件可由Java或Script內產生並共用
3. 搁耻濒别可以更加的动态
Ad

Recommended

Maximise the Power of OSGi - Carsten Ziegeler & David Bosschaert
Maximise the Power of OSGi - Carsten Ziegeler & David Bosschaert
mfrancis
?
CDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily Jiang
mfrancis
?
Osgi cdi
Osgi cdi
Paul Bakker
?
淺談JavaFX 遊戲程式
淺談JavaFX 遊戲程式
CodeData
?
Rule Engine & Drools
Rule Engine & Drools
Sandip Jadhav
?
Rule engine
Rule engine
Gopalakrishnan Shanmugam
?
Drools
Drools
John Paulett
?
Introduction to Rule-based Applications
Introduction to Rule-based Applications
giurca
?
Introduction to Drools
Introduction to Drools
giurca
?
JCConf 2022 - New Features in Java 18 & 19
JCConf 2022 - New Features in Java 18 & 19
Joseph Kuo
?
2011-03-29 London - drools
2011-03-29 London - drools
Geoffrey De Smet
?
Jboss drools 3 key drools functionalities
Jboss drools 3 key drools functionalities
Zoran Hristov
?
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Paul King
?
JavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVM
PaulThwaite
?
Java ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many Languages
elliando dias
?
Rules Programming tutorial
Rules Programming tutorial
Srinath Perera
?
Drools rule Concepts
Drools rule Concepts
RaviShankar Mishra
?
Intro to Drools - St Louis Gateway JUG
Intro to Drools - St Louis Gateway JUG
Ray Ploski
?
JBoss Drools - Open-Source Business Logic Platform
JBoss Drools - Open-Source Business Logic Platform
elliando dias
?
Analysis of software systems using jQAssistant and Neo4j
Analysis of software systems using jQAssistant and Neo4j
Java Usergroup Berlin-Brandenburg
?
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
Jaroslaw Palka
?
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
?
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
?
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
?
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
?
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
?
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
?
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
?
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
?
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
?

More Related Content

Similar to 如何建立公司级应用的商业规则引擎 (13)

Introduction to Drools
Introduction to Drools
giurca
?
JCConf 2022 - New Features in Java 18 & 19
JCConf 2022 - New Features in Java 18 & 19
Joseph Kuo
?
2011-03-29 London - drools
2011-03-29 London - drools
Geoffrey De Smet
?
Jboss drools 3 key drools functionalities
Jboss drools 3 key drools functionalities
Zoran Hristov
?
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Paul King
?
JavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVM
PaulThwaite
?
Java ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many Languages
elliando dias
?
Rules Programming tutorial
Rules Programming tutorial
Srinath Perera
?
Drools rule Concepts
Drools rule Concepts
RaviShankar Mishra
?
Intro to Drools - St Louis Gateway JUG
Intro to Drools - St Louis Gateway JUG
Ray Ploski
?
JBoss Drools - Open-Source Business Logic Platform
JBoss Drools - Open-Source Business Logic Platform
elliando dias
?
Analysis of software systems using jQAssistant and Neo4j
Analysis of software systems using jQAssistant and Neo4j
Java Usergroup Berlin-Brandenburg
?
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
Jaroslaw Palka
?
Introduction to Drools
Introduction to Drools
giurca
?
JCConf 2022 - New Features in Java 18 & 19
JCConf 2022 - New Features in Java 18 & 19
Joseph Kuo
?
Jboss drools 3 key drools functionalities
Jboss drools 3 key drools functionalities
Zoran Hristov
?
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Paul King
?
JavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVM
PaulThwaite
?
Java ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many Languages
elliando dias
?
Rules Programming tutorial
Rules Programming tutorial
Srinath Perera
?
Intro to Drools - St Louis Gateway JUG
Intro to Drools - St Louis Gateway JUG
Ray Ploski
?
JBoss Drools - Open-Source Business Logic Platform
JBoss Drools - Open-Source Business Logic Platform
elliando dias
?
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
Jaroslaw Palka
?

Recently uploaded (20)

Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
?
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
?
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
?
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
?
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
?
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
?
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
?
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
?
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
?
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
?
Wenn alles versagt - IBM Tape schützt, was z?hlt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was z?hlt! Und besonders mit dem neust...
Josef Weingand
?
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
?
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
?
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
?
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
?
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
?
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
?
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
?
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
?
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
?
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
?
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
?
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
?
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
?
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
?
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
?
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
?
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
?
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
?
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
?
Wenn alles versagt - IBM Tape schützt, was z?hlt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was z?hlt! Und besonders mit dem neust...
Josef Weingand
?
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
?
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
?
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
?
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
?
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
?
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
?
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
?
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
?
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
?
Ad

如何建立公司级应用的商业规则引擎