合理的使用规则引擎可以极大的减少代码复杂度,提升代码可维护性。业界知名的开源规则引擎有Drools,功能丰富,但也比较庞大。在一些简单的场景中,我们只需要简易的规则引擎就能满足要求。
本文介绍一个小巧的规则引擎 easy-rules,作为一个lib库提供,支持spring的SPEL表达式,可以很好的集成在spring项目中。
具体的代码参照 示例项目 https://github.com/qihaiyan/springcamp/tree/master/spring-easy-rule
通过将业务规则配置的配置文件中,可以精简代码,同时已于维护,当规则修改时,只需要修改配置文件即可。easy-rules是一个小巧的规则引擎,支持spring的SPEL表达式,同时还支持 Apache JEXL 表达式和 MVL 表达式。
在项目的gradle中增加依赖关系。
build.gradle:
plugins {
id 'org.springframework.boot' version '3.0.5'
id 'io.spring.dependency-management' version '1.1.0'
id 'java'
}
group = 'cn.springcamp'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
testCompileOnly {
extendsFrom testAnnotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation "org.springframework.boot:spring-boot-starter-json"
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.jeasy:easy-rules-core:4.1.0'
implementation 'org.jeasy:easy-rules-spel:4.1.0'
implementation 'org.jeasy:easy-rules-support:4.1.0'
annotationProcessor 'org.projectlombok:lombok'
testAnnotationProcessor 'org.projectlombok:lombok'
testImplementation "org.springframework.boot:spring-boot-starter-test"
testImplementation 'org.junit.vintage:junit-vintage-engine'
testImplementation 'org.junit.vintage:junit-vintage-engine'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:2022.0.1"
}
}
test {
useJUnitPlatform()
}
示例程序将业务规则放到配置文件中,业务规则配置文件(demo-rule.yml)代码:
name: "age rule"
description: ""
priority: 1
condition: "#person.getAdult() == false"
actions:
- "T(java.lang.System).out.println(\"Shop: Sorry, you are not allowed to buy alcohol\")"
- "#person.setAdult(true)"
- "#person.setAge(18)"
---
name: "alcohol rule"
description: ""
priority: 1
condition: "#person.getAdult() == true"
actions:
- "T(java.lang.System).out.println(\"Shop: you are now allowed to buy alcohol\")"
配置文件中的规则通过 condition 进行配置,当满足规则时,会调用 actions 中配置的动作。
示例项目使用了spring的SPEL表达式进行规则配置,配置文件中配置了2个规则,第一个规则通过 person这个spring bean中的getAdult()判断是否满足规则,满足规则时调用三个方法。
在spring-boot本身的配置文件中 application.yml 配置规则文件:
rule:
skip-on-first-failed-rule: true
skip-on-first-applied-rule: false
skip-on-first-non-triggered-rule: true
rules:
- rule-id: "demo"
rule-file-location: "classpath:demo-rule.yml"
通过 RuleEngineConfig这个spring的配置类对规则引擎进行配置:
@Slf4j
@EnableConfigurationProperties(RuleEngineConfigProperties.class)
@Configuration
public class RuleEngineConfig implements BeanFactoryAware {
@Autowired(required = false)
private List<RuleListener> ruleListeners;
@Autowired(required = false)
private List<RulesEngineListener> rulesEngineListeners;
private BeanFactory beanFactory;
@Bean
public RulesEngineParameters rulesEngineParameters(RuleEngineConfigProperties properties) {
RulesEngineParameters parameters = new RulesEngineParameters();
parameters.setSkipOnFirstAppliedRule(properties.isSkipOnFirstAppliedRule());
parameters.setSkipOnFirstFailedRule(properties.isSkipOnFirstFailedRule());
parameters.setSkipOnFirstNonTriggeredRule(properties.isSkipOnFirstNonTriggeredRule());
return parameters;
}
@Bean
public RulesEngine rulesEngine(RulesEngineParameters rulesEngineParameters) {
DefaultRulesEngine rulesEngine = new DefaultRulesEngine(rulesEngineParameters);
if (!CollectionUtils.isEmpty(ruleListeners)) {
rulesEngine.registerRuleListeners(ruleListeners);
}
if (!CollectionUtils.isEmpty(rulesEngineListeners)) {
rulesEngine.registerRulesEngineListeners(rulesEngineListeners);
}
return rulesEngine;
}
@Bean
public BeanResolver beanResolver() {
return new BeanFactoryResolver(beanFactory);
}
@Bean
public RuleEngineTemplate ruleEngineTemplate(RuleEngineConfigProperties properties, RulesEngine rulesEngine) {
RuleEngineTemplate ruleEngineTemplate = new RuleEngineTemplate();
ruleEngineTemplate.setBeanResolver(beanResolver());
ruleEngineTemplate.setProperties(properties);
ruleEngineTemplate.setRulesEngine(rulesEngine);
return ruleEngineTemplate;
}
@Bean
public RuleListener defaultRuleListener() {
return new RuleListener() {
@Override
public boolean beforeEvaluate(Rule rule, Facts facts) {
return true;
}
@Override
public void afterEvaluate(Rule rule, Facts facts, boolean b) {
log.info("-----------------afterEvaluate-----------------");
log.info(rule.getName() + rule.getDescription() + facts.toString());
}
@Override
public void beforeExecute(Rule rule, Facts facts) {
log.info("-----------------beforeExecute-----------------");
log.info(rule.getName() + rule.getDescription() + facts.toString());
}
@Override
public void onSuccess(Rule rule, Facts facts) {
log.info("-----------------onSuccess-----------------");
log.info(rule.getName() + rule.getDescription() + facts.toString());
}
@Override
public void onFailure(Rule rule, Facts facts, Exception e) {
log.info("-----------------onFailure-----------------");
log.info(rule.getName() + "----------" + rule.getDescription() + facts.toString() + e.toString());
}
};
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
配置文件中配置了 ruleEngineTemplate这个spring bean,通过ruleEngineTemplate触发规则引擎的执行。
ruleEngineTemplate配置好后,我们可以在业务代码中执行规则引擎,处理配置文件中配置的业务规则:
最为演示,我们将规则引擎的执行代码放到了 Application 的 run 方法中,程序启动后立即执行规则引擎:
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
RuleEngineTemplate ruleEngineTemplate;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) {
Person person = new Person();
Facts facts = new Facts();
facts.put("person", person);
ruleEngineTemplate.fire("demo", facts);
}
}
程序执行后可以看到控制台里打印了 Shop: Sorry, you are not allowed to buy alcohol,这个内容对应的是我们在规则文件中的actions中配置的 "T(java.lang.System).out.println(\"Shop: Sorry, you are not allowed to buy alcohol\")",说明规则成功执行了。
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我在app/helpers/sessions_helper.rb中有一个帮助程序文件,其中包含一个方法my_preference,它返回当前登录用户的首选项。我想在集成测试中访问该方法。例如,这样我就可以在测试中使用getuser_path(my_preference)。在其他帖子中,我读到这可以通过在测试文件中包含requiresessions_helper来实现,但我仍然收到错误NameError:undefinedlocalvariableormethod'my_preference'.我做错了什么?require'test_helper'require'sessions_hel
我一直很高兴地使用DelayedJob习惯用法:foo.send_later(:bar)这会调用DelayedJob进程中对象foo的方法bar。我一直在使用DaemonSpawn在我的服务器上启动DelayedJob进程。但是...如果foo抛出异常,Hoptoad不会捕获它。这是任何这些包中的错误...还是我需要更改某些配置...或者我是否需要在DS或DJ中插入一些异常处理来调用Hoptoad通知程序?回应下面的第一条评论。classDelayedJobWorker 最佳答案 尝试monkeypatchingDelayed::W
我正在学习Ruby的基础知识(刚刚开始),我遇到了Hash.[]method.它被引入a=["foo",1,"bar",2]=>["foo",1,"bar",2]Hash[*a]=>{"foo"=>1,"bar"=>2}稍加思索,我发现Hash[*a]等同于Hash.[](*a)或Hash.[]*一个。我的问题是为什么会这样。是什么让您将*a放在方括号内,是否有某种规则可以在何时何地使用“it”?编辑:我的措辞似乎造成了一些困惑。我不是在问数组扩展。我明白了。我的问题基本上是:如果[]是方法名称,为什么可以将参数放在括号内?这看起来几乎——但不完全是——就像说如果你有一个方法Foo.d
我想为我的Rails网络应用程序提供推荐功能。特别是,我想向新注册的用户推荐他可能想要关注的其他用户。Rails中是否有用于此目的的引擎/gem?如果没有,我应该从哪里开始构建它?谢谢。 最佳答案 有Coletivogemhttps://github.com/diogenes/coletivo我试了一下。在MySQL上运行。Neo4jhttp://neo4j.org真的很容易实现一个“跟随谁”。事实上,大多数展示其能力的样本都涉及“跟随谁”。快速提示-只有在JRuby上运行时,Neo4j.rb才会很酷。如果不是-使用Neograph
无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD
导读:随着叮咚买菜业务的发展,不同的业务场景对数据分析提出了不同的需求,他们希望引入一款实时OLAP数据库,构建一个灵活的多维实时查询和分析的平台,统一数据的接入和查询方案,解决各业务线对数据高效实时查询和精细化运营的需求。经过调研选型,最终引入ApacheDoris作为最终的OLAP分析引擎,Doris作为核心的OLAP引擎支持复杂地分析操作、提供多维的数据视图,在叮咚买菜数十个业务场景中广泛应用。作者|叮咚买菜资深数据工程师韩青叮咚买菜创立于2017年5月,是一家专注美好食物的创业公司。叮咚买菜专注吃的事业,为满足更多人“想吃什么”而努力,通过美好食材的供应、美好滋味的开发以及美食品牌的孵
一、引擎主循环UE版本:4.27一、引擎主循环的位置:Launch.cpp:GuardedMain函数二、、GuardedMain函数执行逻辑:1、EnginePreInit:加载大多数模块int32ErrorLevel=EnginePreInit(CmdLine);PreInit模块加载顺序:模块加载过程:(1)注册模块中定义的UObject,同时为每个类构造一个类默认对象(CDO,记录类的默认状态,作为模板用于子类实例创建)(2)调用模块的StartUpModule方法2、FEngineLoop::Init()1、检查Engine的配置文件找出使用了哪一个GameEngine类(UGame
C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.
前置步骤我们都操作完了,这篇开始介绍jenkins的集成。话不多说,看操作1、登录进入jenkins后会让你选择安装插件,选择第一个默认的就行。安装完成后设置账号密码,重新登录。2、配置JDK和Git都需要执行路径,所以需要先把执行路径找到,先进入服务器的docker容器,2.1JDK的路径root@69eef9ee86cf:/usr/bin#echo$JAVA_HOME/usr/local/openjdk-82.2Git的路径root@69eef9ee86cf:/#whichgit/usr/bin/git3、先配置JDK和Git。点击:ManageJenkins>>GlobalToolCon