2.yml方式

resources目录下新建fizzbuzz.yml

  1. ---
  2. name: "fizz rule"
  3. description: "print fizz if the number is multiple of 5"
  4. priority: 1
  5. condition: "number % 5 == 0"
  6. actions:
  7. - "System.out.println(\"fizz\")"
  8. ---
  9. name: "buzz rule"
  10. description: "print buzz if the number is multiple of 7"
  11. priority: 2
  12. condition: "number % 7 == 0"
  13. actions:
  14. - "System.out.println(\"buzz\")"
  15. ---
  16. name: "fizzbuzz rule"
  17. description: "print fizzbuzz if the number is multiple of 5 and 7"
  18. priority: 0
  19. condition: "number % 5 == 0 && number % 7 == 0"
  20. actions:
  21. - "System.out.println(\"fizzbuzz\")"
  22. ---
  23. name: "non fizzbuzz rule"
  24. description: "print the number itself otherwise"
  25. priority: 3
  26. condition: "number % 5 != 0 || number % 7 != 0"
  27. actions:
  28. - "System.out.println(number)"

客户端调用:

  1. package com.lrq.wechatdemo.rules;
  2. import org.jeasy.rules.api.Facts;
  3. import org.jeasy.rules.api.Rules;
  4. import org.jeasy.rules.api.RulesEngine;
  5. import org.jeasy.rules.core.DefaultRulesEngine;
  6. import org.jeasy.rules.core.RulesEngineParameters;
  7. import org.jeasy.rules.mvel.MVELRuleFactory;
  8. import java.io.FileNotFoundException;
  9. import java.io.FileReader;
  10. /**
  11. * CreateBy: haleyliu
  12. * CreateDate: 2018/12/26
  13. */
  14. public class RuleYmlClient {
  15. public static void main(String[] args) throws FileNotFoundException {
  16. // create a rules engine
  17. RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(true);
  18. RulesEngine fizzBuzzEngine = new DefaultRulesEngine(parameters);
  19. // create rules
  20. Rules rules = MVELRuleFactory.createRulesFrom(new FileReader("fizzbuzz.yml"));
  21. // fire rules
  22. Facts facts = new Facts();
  23. for (int i = 1; i <= 100; i++) {
  24. facts.put("number", i);
  25. fizzBuzzEngine.fire(rules, facts);
  26. System.out.println();
  27. }
  28. }
  29. }



作者:HaleyLiu
链接:https://www.jianshu.com/p/41ea7a43093c
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。