首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >规则引擎Easy-Rule极简入门

规则引擎Easy-Rule极简入门

作者头像
Antony
发布2020-12-01 18:06:51
发布2020-12-01 18:06:51
2.8K0
举报

Easy-Rule是一个轻量级的规则引擎,也非常容易上手。有了它,“满100减30,满200减60,最高减免xxx”, 程序员就不会因为规则实现错误公司被薅羊毛而被拉去祭天了。

###规则定义

以下是一个官方提供的Helloworld案例。

```

package org.jeasy.rules.tutorials.helloworld;

import org.jeasy.rules.annotation.Action;

import org.jeasy.rules.annotation.Condition;

import org.jeasy.rules.annotation.Rule;

@Rule(name = "Hello World rule", description = "Always say hello world")

public class HelloWorldRule {

@Condition

public boolean when() {

return true;

}

@Action

public void then() {

System.out.println("hello world");

}

}

````

Easy-rule通过@Rule注解来定义规则

@Conition注解的方法来表示条件桩。

@Action方法来表示动作桩。

在一个Rule中,只有当条件桩方法返回值为true时,动作桩方法才会被调用。

Rule注解name、description和priority三个属性。如果有多个规则的话,要保证name的唯一性,另外priority也决定了规则执行的优先顺序。

````

package org.jeasy.rules.annotation;

import java.lang.annotation.ElementType;

import java.lang.annotation.Inherited;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Inherited

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.TYPE})

public @interface Rule {

String name() default "rule";

String description() default "description";

int priority() default 2147483646;

}

````

###规则执行

```

package org.jeasy.rules.tutorials.helloworld;

import org.jeasy.rules.api.Facts;

import org.jeasy.rules.api.Rules;

import org.jeasy.rules.api.RulesEngine;

import org.jeasy.rules.core.DefaultRulesEngine;

public class Launcher {

public static void main(String[] args) {

// create facts

Facts facts = new Facts();

// create rules

Rules rules = new Rules();

rules.register(new HelloWorldRule());

// create a rules engine and fire rules on known facts

RulesEngine rulesEngine = new DefaultRulesEngine();

rulesEngine.fire(rules, facts);

}

}

```

在调用者中,首先定义了规则集Rules,以及Facts这样一个参数map,最后再创建RuleEngine,并调用fire方法,传入rules和facts。

规则引擎会按照优先级逐个调用注册的规则。

后续介绍

-规则引擎停止执行的几种方式:如遇到第一个条件符合/不符合就停止?

-组合规则: 应对规则嵌套等复杂业务需求

-一个规则多动作桩

-Spring整合

最后来看一下实战。阿里也有开源的规则引擎,感兴趣的同学可以翻翻github。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 软件测试那些事 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档