1.什么是Drools
Drools是一個(gè)規(guī)則引擎,可以通過自定義規(guī)則實(shí)現(xiàn)不同的專家語境,而不需要修改源代碼,規(guī)則引擎會(huì)自動(dòng)加載對(duì)應(yīng)的規(guī)則去適應(yīng)不同的場合。
2. 安裝配置Drools環(huán)境
Drools官方下載地址
進(jìn)入網(wǎng)址下載這兩個(gè)壓縮包

下載
解壓放置在一個(gè)文件夾中

解壓完畢
打開Eclipse->Help->install new software->Add->Local->droolsjbpm-tools-distribution-xxx->/binaries/org.drools.updatesite
隨便起一個(gè)名字就可以開始安裝了

安裝
你不要以為點(diǎn)了next就安裝好了!!?。。。。?!
注意看你的eclipse進(jìn)度條,他還在安裝!不要關(guān)?。?!
等他安裝完會(huì)彈出提示的??!
那時(shí)候再重啟eclipse?。?!
(血淚史-0-)
安裝成功過后打開window->perferences看到Drools就說明配置成功了。

image.png

屏幕快照 2018-10-08 18.33.34.png
點(diǎn)擊add,然后browse路徑為剛剛安裝的路徑下的binaries

binaries
然后就加載完成
3.創(chuàng)建一個(gè)Drools項(xiàng)目
New->project->Drools project

選第二個(gè)
這里選擇第二個(gè),因?yàn)榈诙€(gè)有例子!有例子!有例子!
Drools基本規(guī)則可以參考Drools語法規(guī)則
挺全的,但是我用不到那么多。這次的任務(wù)只是通過輸入的分?jǐn)?shù)的多少來評(píng)級(jí)
主函數(shù)實(shí)現(xiàn):
package com.sample;
import java.util.Scanner;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
/**
* This is a sample class to launch a rule.
*/
public class DroolsTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
// go !
Scanner in = new Scanner(System.in);
System.out.println("請(qǐng)輸入需要評(píng)級(jí)的分?jǐn)?shù):(輸入0退出循環(huán))");
int data = in.nextInt();
while(data!=0) {
Score s = new Score(data);
kSession.insert(s);
kSession.fireAllRules();
System.out.println("請(qǐng)輸入需要評(píng)級(jí)的分?jǐn)?shù):(輸入0退出循環(huán))");
data = in.nextInt();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
public static class Score{
public int score;
Score(int Score){
score = Score;
}
public int getScore() {
return score;
}
}
}
規(guī)則文件的編寫
package com.sample
import com.sample.DroolsTest.Score;
rule "ScoreA"
when
Score(score > 90)
then
System.out.println("A");
end
rule "ScoreB+"
when
Score(score >=87&&score<=89)
then
System.out.println("B+");
end
rule "ScoreB"
when
Score(score >=80&&score<=86)
then
System.out.println("B");
end
rule "ScoreC+"
when
Score(score >=77&&score<=79)
then
System.out.println("C+");
end
rule "ScoreC"
when
Score(score >=70&&score<=76)
then
System.out.println("C");
end
rule "ScoreD+"
when
Score(score >=67&&score<=69)
then
System.out.println("D+");
end
rule "ScoreD"
when
Score(score >=60&&score<=66)
then
System.out.println("D");
end
rule "ScoreF"
when
Score(score < 60)
then
System.out.println("F");
end
當(dāng)我們運(yùn)行時(shí),輸入1-100的數(shù)值,可以輸出對(duì)應(yīng)的評(píng)級(jí)

效果
結(jié)語:雖然看起來這個(gè)例子好像很傻的樣子,但是在實(shí)際的應(yīng)用過程中,如果我們要實(shí)現(xiàn)評(píng)級(jí),不需要像往常一樣,修改什么case 啊之類的源碼,我們僅僅需要修改規(guī)則,就可以實(shí)現(xiàn)一樣的效果,這是很有用的,很利于我們維護(hù)代碼
友情鏈接:
Drols入門環(huán)境配置
Drools應(yīng)用場景-小明的煩惱<---------很有趣可以看看