JAVA规则引擎[Drools]--实例篇

随着互联网应用的飞速发展,各种业务需求也应运而生,对于不断变更和革新的业务规则而言,项目的开发就很有必要把规则部分独立提取出来,此时Drools的价值就得到了体现。废话不多说,看一个简单的例子。

这里举一个手机话费的例子。

一、定义规则:

首先要分析自己的业务逻辑,根据业务而制定出不同的规则,这里我们假设有3个规则。

1、对于新开户的手机用户送20元话费。

2、在2014年10月到12期间充值的用户,不论金额多少充值满3次就赠送5元话费。

3、当月充值金额达到100以上,每达到一次赠送话费10元。

二、创建Fact对象:

分析这些规则,并把他们抽象成一个Fact对象。

package com.core.drools;

import java.util.UUID;

/**

三、定义规则引擎:

业务和规则都整理清楚了我们就可以开始规则引擎的核心部分啦,这里我定义的是接口和实现类。

package com.core.drools;

/**

}

package com.core.drools;

import java.io.File;

/**

RuleEngine{

"yyyy-MM-dd HH:mm:ss");

ageBuilderFile();

getPackages());

/*

(com.core.drools.EntityRule)

ruleBase.newStatefulSession();

drools.spi.AgendaFilter() {

contains("_test");

erFile()throws Exception {

getErrors().toString());

<String> drlFilePath)

/**

com/core/drools/drools_rule.drl";

}

这里定义一个单例的RuleBase工厂类。

package com.core.drools;

import org.drools.RuleBase;

/**

}

四、编写规则文件:

规则文件可以根据自己的业务需求定义多个文件,这里我只定义了一个。

package com.core.drools

import com.core.drools.EntityRule;

rule accountEntity

¥20.0");

getCurrentmoney()+20);

getUsername(),$entityRule.getCurrentmoney());

rule billEntity

reach "+$entityRule.getAddtime()

getCurrentmoney()+$entityRule.getAddtime()/3*5);

getUsername(),$entityRule.getCurrentmoney());

rule addMoney

the month top-up totail amount is "

getUsername(),$entityRule.getCurrentmoney());

五、测试引擎:

package com.test;

import java.io.IOException;

/**

六、测试结果:

The new account:Present ¥20.0

Account:Candy Balance:¥370.0

Serial Number:0fd98593-caa2-444d-a4ff-b4001cfb3260

------------------------------------------------------------------------------

Prepaid phone number reach 7 times:Present ¥10

Account:Candy Balance:¥380.0

Serial Number:a118b211-c28e-4035-aa60-2f417f62b2f3

------------------------------------------------------------------------------

The account for the month top-up totail amount is 350.0: Present ¥30

Account:Candy Balance:¥410.0

Serial Number:2bfc02c2-267f-47a2-9cda-5a4196e2b7cf

出处:http://www.uml.org.cn/j2ee/201803271.asp



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值