easy-rules
我们在写业务代码经常遇到需要一大堆if/else,会导致代码可读性大大降低,有没有一种方法可以避免代码中出现大量的判断语句呢?答案是用规则引擎,但是传统的规则引擎都比较重,比如开源的Drools,不适合在小需求中应用。最近在github上面看到一个傻瓜式的Java规则引擎Easy-Rules,这里结合自己写的demo介绍如何使用这个规则引擎,希望对大家有所帮助。
easy-rules的特点
- 轻量级类库和容易上手
- 基于POJO的开发与注解的编程模型
- 基于MVEL表达式的编程模型(适用于极简单的规则,一般不推荐)
- 支持根据简单的规则创建组合规则
- 方便且适用于java的抽象的业务模型规则
它主要包括几个主要的类或接口:Rule,RulesEngine,RuleListener,Facts
还有几个主要的注解:@Action,@Condition,@Fact,@Priority,@Rule
例1:基于POJO开发与注解的编程模型:判断1-50中,被3或者8整除的数
- 首先maven 引入easy-rules
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-mvel</artifactId>
<version>3.3.0</version>
</dependency>
- 编写规则POJO:
@Rule(name = "被3整除", description = "number如果被3整除,打印:number is three")
public class ThreeRule {
@Condition //条件判断注解:如果return true, 执行Action
public boolean isThree(@Fact("number") int number){
return number % 3 == 0;
}
@Action //执行方法注解
public void threeAction(@Fact("number") int number){
System.out.print(number + " is three");
}
@Priority //优先级注解:return 数值越小,优先级越高
public int getPriority(){
return 1;
}
}
@Rule(name = "被8整除")
public class EightRule {
@Condition
public boolean isEight(@Fact("number") int number){
return number % 8 == 0;
}
@Action
public void eightAction(@Fact("number") int number){
System.out.print(number + " is eight");
}
@Priority
public int getPriority(){
return 2;
}
}
@Rule(name = "被3和8同时整除", description = "这是一个组合规则")
public class ThreeEightRuleUnitGroup extends UnitRuleGroup {
public ThreeEightRuleUnitGroup(Object... rules) {
for (Object rule : rules) {
addRule(rule);
}
}
@Override
public int getPriority() {
return 0;
}
}
@Rule(name = "既不被3整除也不被8整除", description = "打印number自己")
public class OtherRule {
@Condition
public boolean isOther(@Fact("number") int number){
return number % 3 != 0 || number % 8 != 0;
}
@Action
public void printSelf(@Fact("number") int number){
System.out.print(number);
}
@Priority
public int getPriority(){
return 3;
}
}
- 执行规则
public class ThreeEightRuleLauncher {
public static void main(String[] args) {
/**
* 创建规则执行引擎
* 注意: skipOnFirstAppliedRule意思是,只要匹配到第一条规则就跳过后面规则匹配
*/
RulesEngineParameters parameters = new
RulesEngineParameters().skipOnFirstAppliedRule(true);
RulesEngine rulesEngine = new DefaultRulesEngine(parameters);
//创建规则
Rules rules = new Rules();
rules.register(new EightRule());
rules.register(new ThreeRule());
rules.register(new ThreeEightRuleUnitGroup(new EightRule(), new ThreeRule()));
rules.register(new OtherRule());
Facts facts = new Facts();
for (int i=1 ; i<=50 ; i++){
//规则因素,对应的name,要和规则里面的@Fact 一致
facts.put("number", i);
//执行规则
rulesEngine.fire(rules, facts);
System.out.println();
}
}
}
- 我们可以得到执行结果
1
2
3 is three
4
5
6 is three
7
8 is eight
9 is three
10
11
12 is three
13
14
15 is three
16 is eight
17
18 is three
19
20
21 is three
22
23
24 is three24 is eight
25
26
27 is three
28
29
30 is three
31
32 is eight
33 is three
34
35
36 is three
37
38
39 is three
40 is eight
41
42 is three
43
44
45 is three
46
47
48 is three48 is eight
49
50
例2:基于MVEL表达式的编程模型
本例演示如何使用MVEL表达式定义规则,MVEL通过Easy-Rules MVEL模块提供。此模块包含使用MVEL定义规则的API。我们将在这里使用这些API,其目标是实现一个简单的商店应用程序,要求如下:禁止儿童购买酒精,成年人的最低法定年龄为18岁。 商店顾客由Person类定义:
public class Person {
private String name;
private boolean adult;
private int age;
//getter, setter 省略
}
我们定义两个规则:
- 规则1:可以更新Person实例,判断年龄是否大于18岁,并设置成人标志。
- 规则2:判断此人是否为成年人,并拒绝儿童(即非成年人)购买酒精。
显然,规则1的优先级要大于规则2,我们可以设置规则1的Priority为1,规则2的Priority为2,这样保证规则引擎在执行规则的时候,按优先级的顺序执行规则。
规则1的定义
Rule ageRule = new MVELRule()
.name("age rule")
.description("Check if person's age is > 18 and marks the person as adult")
.priority(1)
.when("person.age > 18")
.then("person.setAdult(true);");
规则2的定义,我们放到alcohol-rule.yml文件中
name: "alcohol rule"
description: "children are not allowed to buy alcohol"
priority: 2
condition: "person.isAdult() == false"
actions:
- "System.out.println(\"Shop: Sorry, you are not allowed to buy alcohol\");"
- 执行规则
public class ShopLauncher {
public static void main(String[] args) throws Exception {
//创建一个Person实例(Fact)
Person tom = new Person("Tom", 14);
Facts facts = new Facts();
facts.put("person", tom);
//创建规则1
Rule ageRule = new MVELRule()
.name("age rule")
.description("Check if person's age is > 18 and marks the person as adult")
.priority(1)
.when("person.age > 18")
.then("person.setAdult(true);");
//创建规则2
Rule alcoholRule = MVELRuleFactory.createRuleFrom(new FileReader("alcohol-rule.yml"));
Rules rules = new Rules();
rules.register(ageRule);
rules.register(alcoholRule);
//创建规则执行引擎,并执行规则
RulesEngine rulesEngine = new DefaultRulesEngine();
System.out.println("Tom: Hi! can I have some Vodka please?");
rulesEngine.fire(rules, facts);
}
}
- 执行结果如下:
本篇主要介绍easy-rules的使用
easy-rules的更多相关文章
- Java规则引擎 Easy Rules
1. Easy Rules 概述 Easy Rules是一个Java规则引擎,灵感来自一篇名为<Should I use a Rules Engine?>的文章 规则引擎就是提供一种可选 ...
- 小明历险记:规则引擎drools教程一
小明是一家互联网公司的软件工程师,他们公司为了吸引新用户经常会搞活动,小明常常为了做活动加班加点很烦躁,这不今天呀又来了一个活动需求,我们大家一起帮他看看. 小明的烦恼 活动规则是根据用户购买订单的金 ...
- Java中动态规则的实现方式
背景 业务系统在应用过程中,有时候要处理“经常变化”的部分,这部分需求可能是“业务规则”,也可能是“不同的数据处理逻辑”,这部分动态规则的问题,往往需要可配置,并对性能和实时性有一定要求. Java不 ...
- 实时营销引擎在vivo营销自动化中的实践 | 引擎篇04
作者:vivo 互联网服务器团队 本文是<vivo营销自动化技术解密>的第5篇文章,重点分析介绍在营销自动化业务中实时营销场景的背景价值.实时营销引擎架构以及项目开发过程中如何利用动态队列 ...
- The Nine Indispensable Rules for HW/SW Debugging 软硬件调试之9条军规
I read this book in the weekend, and decided to put the book on my nightstand. It's a short and funn ...
- Website Speed Optimization Guide for Google PageSpeed Rules
原链接地址:http://www.artzstudio.com/2016/07/website-speed-optimization-guide-for-google-pagespeed-rules/ ...
- jQuery Easy UI 开发笔记
1.jQuery Easy UI主要的运行原理是通过核心的代码调用插件来实现UI效果的 2.jQuery Easy UI插件与插件之间的关系是: 一.独立式插件: 独立式插件是指:不与其他的插件具有相 ...
- acdream.A Very Easy Triangle Counting Game(数学推导)
A - A Very Easy Triangle Counting Game Time Limit:1000MS Memory Limit:64000KB 64bit IO Forma ...
- 转载:10 Easy Steps to a Complete Understanding of SQL
10 Easy Steps to a Complete Understanding of SQL 原文地址:http://tech.pro/tutorial/1555/10-easy-steps-to ...
- [转]java-Three Rules for Effective Exception Handling
主要讲java中处理异常的三个原则: 原文链接:https://today.java.net/pub/a/today/2003/12/04/exceptions.html Exceptions in ...
随机推荐
- knitr::kable实现结构化展示数据
一般做检验,直接会summary结果,通常情况下,会看到很多很多,口区~ 如何提取有用的信息,然后结构化展示数据呢? kable函数了. 我先给出学长给我的一部分,回头整理好了再补充 culture_ ...
- 【巨杉数据库SequoiaDB】SequoiaDB 巨杉数据库 v3.4 版本正式发布
深秋时节,SequoiaDB 巨杉数据库在深秋给大家带来了“一把火”.SequoiaDB v3.4 正式发布啦! 分布式交易场景性能大幅提升 SequoiaDB 巨杉数据库3.4版本正式发布,v3.4 ...
- 洛谷P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here
题目描述 众所周知,在每一个彗星后都有一只UFO.这些UFO时常来收集地球上的忠诚支持者.不幸的是,他们的飞碟每次出行都只能带上一组支持者.因此,他们要用一种聪明的方案让这些小组提前知道谁会被彗星带走 ...
- PP: GRU-ODE-Bayes: Continuous modeling of sporadically-observed time series
From: KU Leuven; ESAT-STADIUS比利时鲁汶大学 ?? How to model real-world multidimensional time series? especi ...
- 逆战:微信小程序(一)
简介 小程序是一种不需要下载安装即可使用的应用,它实现了应用"触手可及"的梦想,用户扫一扫或者搜一下即可打开应用.也体现了"用完即走"的理念,用户不用关心是否安 ...
- webpack 之loader
webpack的作用: 是 用来处理我们写的js代码.并且会自动处理js之间相关的依赖. 但是,开发中我们不仅仅有基本的js代码处理,还需要加载css,图片,也包括一些高级的 将ES6转成ES5代 ...
- LVS+Nginx(LVS + Keepalived + Nginx安装及配置)
(也可以每个nginx都挂在上所有的应用服务器) nginx大家都在用,估计也很熟悉了,在做负载均衡时很好用,安装简单.配置简单.相关材料也特别多. lvs是国内的章文嵩博士的大作,比nginx被广 ...
- 表结构修改以及sql增删改查
修改表结构 修改表名 alter table 表名 rename 新名 增加字段 alter table 表名 add 字段名 数据类型 约束 删除字段 alter table 表名 drop 字段名 ...
- 二、vim的保存文件和退出命令
vim的保存文件和退出命令 命令 简单说明 :w 保存编辑后的文件内容,但不退出vim编辑器.这个命令的作用是把内存缓冲区中的数据写到启动vim时指定的文件中. :w! 强制写文件,即强制覆盖原有 ...
- batchsize用法 以及实现前向运算的矩阵乘法方式
batchsize用法 以及实现前向运算的矩阵乘法方式 待办 使用batchsize可以把矩阵缩小,采用矩阵乘法的形式可以一次计算多个经过神经网络的结果,然后通过交叉熵进行计算总的损失得到结果. 所以 ...