2.yml方式
resources目录下新建fizzbuzz.yml
- ---
- name: "fizz rule"
- description: "print fizz if the number is multiple of 5"
- priority: 1
- condition: "number % 5 == 0"
- actions:
- - "System.out.println(\"fizz\")"
-
- ---
- name: "buzz rule"
- description: "print buzz if the number is multiple of 7"
- priority: 2
- condition: "number % 7 == 0"
- actions:
- - "System.out.println(\"buzz\")"
-
- ---
- name: "fizzbuzz rule"
- description: "print fizzbuzz if the number is multiple of 5 and 7"
- priority: 0
- condition: "number % 5 == 0 && number % 7 == 0"
- actions:
- - "System.out.println(\"fizzbuzz\")"
-
- ---
- name: "non fizzbuzz rule"
- description: "print the number itself otherwise"
- priority: 3
- condition: "number % 5 != 0 || number % 7 != 0"
- actions:
- - "System.out.println(number)"
客户端调用:
- package com.lrq.wechatdemo.rules;
-
- 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;
- import org.jeasy.rules.mvel.MVELRuleFactory;
-
- import java.io.FileNotFoundException;
- import java.io.FileReader;
-
- /**
- * CreateBy: haleyliu
- * CreateDate: 2018/12/26
- */
- 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);
-
- // create rules
- Rules rules = MVELRuleFactory.createRulesFrom(new FileReader("fizzbuzz.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();
- }
- }
- }
作者:HaleyLiu
链接:https://www.jianshu.com/p/41ea7a43093c
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。