千家信息网

怎么理解java规则引擎

发表于:2024-10-22 作者:千家信息网编辑
千家信息网最后更新 2024年10月22日,本篇内容主要讲解"怎么理解java规则引擎",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"怎么理解java规则引擎"吧!WHAT规则引擎由推理引擎发展而来,
千家信息网最后更新 2024年10月22日怎么理解java规则引擎

本篇内容主要讲解"怎么理解java规则引擎",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"怎么理解java规则引擎"吧!

WHAT

规则引擎由推理引擎发展而来,是一种嵌入在应用程序中的组件,实现了将业务决策从应用程序代码中分离出来,并使用预定义的语义模块编写业务决策。接受数据输入。解释业务规则,并根据业务规则作出业务决策。在Java中,大多数的规则引擎都实现JSR94。将规则引擎想象成一个以数据和规则作为输入的系统。他讲这些规则定义为我们提供输出

if x then y

WHY

我们的业务代码里充斥了大量的if/else,当然,我们可以用策略模式+模板模式将if/else抽到各个子类中。但是也增加了类的复杂度。

硬编码

如果需要修改Java类中的逻辑,在更改进入生产环境前,将会精力一个冗长的过程

  1. 硬编码开发

  2. 测试代码

  3. 审核代码

  4. 部署代码

引入规则引擎

服务接口单纯化,将复杂多变的业务逻辑交给比高级语言更加接近自然语言的规则,让用户在web端或cs端自己进行配置发布,将技术和业务逻辑解耦。

常用框架

drools

谷歌出品的规则引擎框架,也是很多公司选型的第一选择。基于Charles Forgy's的RETE算法,易于调整以及易于管理的开源业务规则引擎,符合业内标准、速度快、效率高。业务分析人员或审核人员可以利用给他轻松查看业务规则,检验已编码的规则执行了所需业务规则。一般企业都会做二次开发,并且有web端可视化操作界面。

demo

无spring版本,maven引入drools

        org.kie        kie-api        6.3.0.Final        org.drools        drools-core        6.3.0.Final        org.drools        drools-compiler        6.3.0.Final        org.drools        drools-decisiontables        6.3.0.Final        org.drools        drools-templates        6.3.0.Final

需要在resources下增加META-INF文件夹,并且创建kmodule.xml声明规则文件的关系

                                

编写规则文件,在resources下创建rules1文件夹,保证和xml文件中的packages一致。新建rule.drl文件,语法有点类似java,最后还是要转成java的

pacage com.ruleengine.drools// 导入自定义实体类import com.ruleengine.drools.Message// 规则名rule 'VIP'        when            // 进入条件为 status是VIP,并且把message属性给到printMsg,否则外部无法使用                m : Message( status == Message.VIP , printMsg : message )         then                System.out.println( printMsg );                m.setMessage( "普通用户不打折" );                m.setStatus( Message.COMMON_USER );                // 更新实体                update( m );end// 第二个规则rule "commonUser"        when                Message( status == Message.COMMON_USER, printMsg : message )        then                System.out.println( printMsg );end

调用

public class DroolsMain{        public static void main(String[] args){                KieServices kieServices = KieServices.Factory.get();                KieContainer kieContainer = kieServices.getKieClasspathContainer();                KieSession kSession = kieContainer.newKieSession("ksession-rules");                Message m = new Message();                m.setMessage("VIP打折");                m.setStatus(Message.VIP);                // 将实体类插入执行规则                kSession.insert(m);                kSession.fireAllRules();        }}

自定义类

public class Message{        public static final int VIP - 1;        public staitc final int COMMON_USER = 0;        private String message;        private String status;        public String getMessage(){return this.message;}        public int getStatus(){ return this.status; }        public void setMessage(String message){ this.message = message; }        public void setStatus(int status){ this.status = status; }}

特色代表-有赞

有赞最终选择了drools规则引擎来做风控逻辑。用来防御以下风险:

  • 盗卡。例:盗用用户银行卡,在有赞店铺上消费

  • 欺诈。例:通过发布低价商品,诱骗消费者购买

  • 套现。例:在自己创建的店铺里进行虚假交易用以套现信用卡

  • 垃圾信息。例:发布虚假消息、色情等违规商品、页面

  • 盗账户。例:黑客用其他平台获取的账户密码通过撞库来非法盗取用户在赞平台的账户

from https://tech.youzan.com/rules-engine/

easyrule

https://github.com/j-easy/easy-rules

特点

  • 轻量级框架和易于学习的API

  • 基于POJO的开发和注解的编程模型

  • 支持从简单规则创建组合规则的能力

  • 支持使用表达式语言(如MVEL和SpEL),最新版本支持JEXL

概念

  • facts 规则引擎输入

  • rule 规则 rules 规则集合

  • condition 匹配条件

  • action 执行动作

两种方式定义规则

  • 通过在POJO上添加注释,以声明的方式定义

  • 通过RuleBuilder API,以编程方式定义

更多案例可以到这看 https://github.com/j-easy/easy-rules/tree/master/easy-rules-tutorials

maven引入,最新版本
        org.jeasy        easy-rules-core        4.1.0
POJO
package com.lrq.wechatdemo.rules; import org.jeasy.rules.annotation.Action;import org.jeasy.rules.annotation.Condition;import org.jeasy.rules.annotation.Fact;import org.jeasy.rules.annotation.Rule;import org.jeasy.rules.support.UnitRuleGroup;public class RuleClass {     @Rule(priority = 1) //规则设定优先级    public static class FizzRule {        @Condition // 返回值为boolean        public boolean isFizz(@Fact("number") Integer number) {            return number % 5 == 0;        }         @Action        public void printFizz() {            System.out.print("fizz\n");        }    }     @Rule(priority = 2)    public static class BuzzRule {        @Condition        public boolean isBuzz(@Fact("number") Integer number) {            return number % 7 == 0;        }         @Action        public void printBuzz() {            System.out.print("buzz\n");        }    }     public static class FizzBuzzRule extends UnitRuleGroup {         public FizzBuzzRule(Object... rules) {            for (Object rule : rules) {                addRule(rule);            }        }         @Override        public int getPriority() {            return 0;        }    }     @Rule(priority = 3)    public static class NonFizzBuzzRule {         @Condition        public boolean isNotFizzNorBuzz(@Fact("number") Integer number) {            // can return true, because this is the latest rule to trigger according to            // assigned priorities            // and in which case, the number is not fizz nor buzz            return number % 5 != 0 || number % 7 != 0;        }         @Action        public void printInput(@Fact("number") Integer number) {            System.out.print(number+"\n");        }    } }

调用

import org.jeasy.rules.api.Facts;import org.jeasy.rules.api.Rules;import org.jeasy.rules.api.RulesEngine;import org.jeasy.rules.core.DefaultRulesEngine;import org.jeasy.rules.core.RulesEngineParameters; public class RuleJavaClient {    public static void main(String[] args) {        // 创建规则引擎        RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(true);        RulesEngine fizzBuzzEngine = new DefaultRulesEngine(parameters);         // 创建规则集并注册规则        Rules rules = new Rules();        rules.register(new RuleClass.FizzRule());        rules.register(new RuleClass.BuzzRule());        rules.register(new RuleClass.FizzBuzzRule(new RuleClass.FizzRule(), new RuleClass.BuzzRule()));        rules.register(new RuleClass.NonFizzBuzzRule());         // 执行规则        Facts facts = new Facts();        for (int i = 1; i <= 100; i++) {            facts.put("number", i);            fizzBuzzEngine.fire(rules, facts);            System.out.println();        }    } }
yml

在resources下新建yml文件

---name: "fizz rule"description: "print fizz if the number is multiple of 5"priority: 1condition: "number % 5 == 0"actions:- "System.out.println(\"fizz\")" ---name: "buzz rule"description: "print buzz if the number is multiple of 7"priority: 2condition: "number % 7 == 0"actions:- "System.out.println(\"buzz\")" ---name: "fizzbuzz rule"description: "print fizzbuzz if the number is multiple of 5 and 7"priority: 0condition: "number % 5 == 0 && number % 7 == 0"actions:- "System.out.println(\"fizzbuzz\")" ---name: "non fizzbuzz rule"description: "print the number itself otherwise"priority: 3condition: "number % 5 != 0 || number % 7 != 0"actions:- "System.out.println(number)"

调用,将yml解析为rules

public class RuleYmlClient {     public static void main(String[] args) throws FileNotFoundException {        // create a rules engine        RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(true);        RulesEngine fizzBuzzEngine = new DefaultRulesEngine(parameters);         // load rules from yml                MVELRuleFactory fuleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader())        Rules rules = fuleFactory.createRules(new FileReader("rule.yml"));         // fire rules        Facts facts = new Facts();        for (int i = 1; i <= 100; i++) {            facts.put("number", i);            fizzBuzzEngine.fire(rules, facts);            System.out.println();        }    }}

URule

国内的规则引擎,和drool一样基于RETE算法建立的。URule Pro是一款由上海锐道信息技术有限公司自主研发的一款纯Java规则引擎,它可以运行在Windows、Linux、Unix等各种类型的操作系统之上; URule Pro的规则设计器采用业内首创的纯浏览器编辑模式,无须安装任何工具,打开浏览器即可完成复杂规则的设计与测试。


旗正规则引擎

旗正规则引擎是由国家科技部和财政部的创新基金支持,专门针对国内规则引擎市场空白的情况,结合国内项目的特点而开发的一款业务规则管理系统(BRMS)产品。规则引擎以规则配置编辑器为规则录入窗口,以规则引擎为系统运转动力,以企业规则库为业务逻辑基础,辅以规则协同管理、远程项目与服务管理、集群规则同步等功能模块,实现业务逻辑的可视化定制,同时又具有快速开发java软件项目的功能

国内比较大的商业级规则引擎,有专用的CS客户端。并且支持规则测试、调用外部规则包、操作数据库、解析excel等骚操作。

到此,相信大家对"怎么理解java规则引擎"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0