How Java rule engine works and its practical application

Source: Internet
Author: User

Currently, the Java Community has promoted and developed a compelling new technology-the Java rule engine ). With this feature, business decision-making logic of commercial decision makers and technical decisions of application developers can be separated in the application system, and these commercial decisions can be placed in the central database or other unified places, it enables them to dynamically manage and modify at runtime, so as to provide effective technical support for enterprises to maintain flexibility and competitiveness.

  Rule Engine Principles

1. Introduction to rule-based Expert System (RBEs)

The Java Rule Engine originated from the rule-based expert system, and the rule-based expert system is one of the branches of the expert system. An expert system belongs to the category of artificial intelligence. It imitates human reasoning methods, uses exploratory methods for reasoning, and uses terminologies that humans can understand to explain and prove their reasoning conclusions. To gain a deeper understanding of the Java rule engine, we will briefly introduce the rule-based expert system. RBEs includes three parts: Rule Base (knodge DGE base), working memory (fact base), and inference engine. Their structure is as follows:


Figure 1 Composition of a rule-based Expert System

1. the inference engine consists of pattern matcher, agenda, and execution engine ). The inference engine is added to the agenda by deciding which rules meet the facts or goals and granting the rule priority. Pattern Matching determines which rule to execute and when to execute the rule. The execution sequence of the Rule selected by the pattern matching in the agenda management mode. The execution engine is responsible for executing the rule and other actions.

In contrast to human thinking, the inference engine has two ways of reasoning: Forward-chaining and backward-chaining ). The attention method starts from an initial fact and constantly applies rules to draw conclusions (or execute specified actions ). The induction rule is to constantly find facts that conform to the assumptions based on assumptions. The Rete algorithm is currently the most efficient forward-chaining inference algorithm. Many Java rule engines use the Rete algorithm for inference and calculation.

The reasoning process of the inference engine is as follows:

(1) input the initial data (fact) into working memory.

(2) Use Pattern matcher to compare the Rules (rule) and data (fact) in the rule base ).

(3) If the execution rule has a conflict (conflict), that is, multiple rules are activated at the same time, and conflicting rules are put into the conflict set.

(4) resolve the conflict and add the activated rules to agenda in sequence.

(5) use the execution engine to execute the rules in agenda. Repeat steps 2 to 5 until all the rules in agenda are executed.

The above is the original architecture of the rule engine, and the Java Rule Engine evolved from this original architecture.

2. Rules Engine Components

The rule engine is an engine that determines whether a rule can match a real-time condition at the runtime Based on the specified filter conditions contained in the rule to execute the action specified in the rule. There are four basic concepts related to the rule engine. To better understand the working principles of the Rule engine, we will introduce these concepts one by one.

1) Information Unit)

Information Meta is the basic building block of the rule engine. It is an object that contains all information about a specific event. The information includes the message, Application ID of the event generation, event generation event, information meta-type, related rule set, general method, general attributes, and some system-related information.

2) Information Services)

Information service generates metadata objects. Each information service generates information meta objects corresponding to its own type. That is, each metadata object generated by a specific information service according to the metadata has the same format, but can have different attributes and rule sets. It should be noted that many different information services can be run on one machine, and different instances of the same information service can be run. However, in any case, each information service only generates information elements corresponding to its own type.

3) Rule Set)

As the name implies, a rule set is a set of many rules. Each rule contains one filter and multiple actions. A filter can contain multiple filtering conditions. A condition filter is a combination of multiple boolean expressions, and the combination result is still a boolean type. When the program runs, the action is executed when the condition filter value is true. In addition to general execution actions, there are three special actions: discard action, include action, and action that persists the content of the information metadata object. The differences between the first two types of actions are described in section 2.3 rule engine working mechanism.

4) Queue Manager)

The queue manager is used to manage queues of Information metadata objects from different information services.

The following describes how these components of the Rule Engine Work collaboratively.

As shown in 2, the processing process is divided into four stages: Information Service accepts the event and converts it into information elements, which are then transmitted to the queue manager, finally, the Rule Engine receives the information elements and applies the rules they carry to execute them until there is no information element in the queue manager.


Figure 2 Process Collaboration Diagram

3. Rule Engine Working Mechanism

The following describes the internal processing of the rule engine. As shown in 3, the Rule Engine receives information elements from the queue manager in sequence, and then checks the rules in the Rule Set in the order defined by the rules ., The rule engine checks the first rule and evaluates its condition filter. If the value is false, all actions related to the rule are ignored and the next rule is executed. If the filter value of the second rule is true, all actions related to the rule are executed in the defined order. After the rule is executed, the next rule is continued. After all the rules in the information element are executed, the information element will be destroyed and the next information element will be received from the queue manager. Two special actions are not taken into account in this process: discard action and include action ). If the discard action is executed, all the following rules in the information element will be skipped and the information element will be destroyed. The rule engine will continue to receive the next information element in the queue manager. Include actions are actions that contain other existing rule sets. If the contained action is executed, the rule engine will pause and enter the contained rule set. After the execution is completed, the rule engine will return to the previously paused place for further execution. This process is recursive.


Figure 3 Rule Engine Working Mechanism

The working mechanism of the Java rule engine is similar to that of the rule engine, but the above concepts are repackaged and combined. The Java rule engine searches for the Java Data Objects submitted to the engine. Based on the current attribute values of these objects and their relationships, the Rules loaded to the engine can find matching rules in a centralized manner, create execution instances for these rules. These instances are executed sequentially when the engine receives the execution instructions. Generally, the Java rule engine consists of the following components: Working Memory (Working Memory), a workspace, used to store a collection of data objects referenced by the engine; rule execution queue, it is used to store activated rule execution instances. The static rule area is used to store all loaded business rules. These rules are organized according to a certain data structure. When the data in the workspace changes, the engine needs to quickly adjust the rule execution instances in the rule execution Queue according to the current situation of objects in the workspace. The structure 4 of the Java rule reference is shown in.


Figure 4 Working Mechanism of the Java Rule Engine

When the engine is executed, the instance is executed according to the priority in the rule execution queue. Because the execution part of the rule may change the data object in the workspace, in this way, some rules in the queue will invalidate the instance because of the change of conditions. The instance must be revoked from the queue, or the rule that originally did not meet the conditions may be activated, generate a new rule execution instance and enter the queue. Therefore, a "dynamic" rule execution chain is created to form a rule reasoning mechanism. The "chain" reaction of such rules is entirely driven by the data in the workspace.

Any rule engine needs to solve the problem of the Efficiency of Rule Inference Mechanism and rule condition matching. The efficiency of Rule condition matching determines the performance of the engine. The engine needs to quickly test the data objects in the workspace, find matching rules from the loaded rules, and generate rule execution instances. In 1982, Charles L. forgy from Carnegie Mellon University in the United States invented a Rete algorithm, which effectively solved this problem. Currently, rete algorithms are basically used in the world's top commercial business rule engine products.

 Java Rule Engine API--JSR-94

To standardize the rules engine technology, the Java Community has developed the Java Rule Engine API (jsr94) specification. It defines some simple APIs for the access rule engine of the Java platform.

The Java Rule Engine API is defined in the javax. Rules package and is a standard enterprise-level API for accessing the rule engine. The Java Rule Engine API allows a client program to interact with different manufacturers' Rule Engine products in a uniform way, just as if the JDBC program was used to write a database product independent of the vendor to access different database products. The Java Rule Engine API includes a mechanism for creating and managing rule sets, a mechanism for adding, deleting, and modifying objects in the workspace, and a mechanism for initializing, resetting, and executing the rule engine.

1. Java Rule Engine API Architecture

The Java Rule Engine API consists of the rule management API (the Rules administrator API) and the runtime client API (the runtime client API ).

1) rule management API

The rule management API is defined in javax. Rules. Admin, including loading rules, corresponding actions (Execution sets of execution sets) of rules, and instantiation rule engine. Rules can be loaded from external resources, such as Uri, input streams, XML streams, and readers. Meanwhile, the rule management API also provides a mechanism for registering and canceling an execution set and maintaining the execution set. The use of admin package definition rules helps to control and manage the access and operation rules of the customer. It defines the permission on the execution set so that unauthorized users cannot access the controlled rules.

The rule management API uses the ruleserviceprovider class to obtain the instance of the Rule Manager interface. This interface provides method registration and cancellation of registration execution sets. The rule manager provides local and remote ruleexecutionsetprovider, which is responsible for creating the rule execution set (ruleexecutionset ). Rule execution sets can be created from sources such as XML streams and binary streams. These data sources and their content are collected and serialized and then transmitted to the server that runs the Rule Engine remotely. In most applications, the remote rule engine or remote rule data sources are not many. To avoid network overhead in these cases, the API specifies the local ruleexecutionsetprovider that can read data from the rule repository running in the same JVM. The rule execution set interface not only provides methods for obtaining the rule execution set, but also allows you to retrieve all rule objects defined in the rule execution set. This allows the customer to know the rule objects in the Rule Set and use them as needed.

2) Customer API at runtime

The Runtime API is defined in the javax. Rules package and provides classes and methods for the rule engine users to obtain the results of running rules. During running, the customer can only access those rules registered using the rule management API. During running, the API helps the user obtain the rule session and execute the rule in this session.

The Runtime API provides access to the vendor's Rule Engine API, which is similar to JDBC. The class ruleserviceprovider provides access to the runtime and Management APIs implemented by the specific rule engine. The rule engine vendor provides its rule engine implementation to customers through this class, obtain the URL that uniquely identifies the rule engine of ruleserviceprovider. The standard usage of this URL is to use an Internet Domain Name Space similar to "com. mycompany. myrulesengine. Rules. ruleserviceprovider", which ensures the uniqueness of the access URL. Class ruleserviceprovider internally implements the interface required for rule management and runtime access. All ruleserviceproviders must be registered with ruleserviceprovidermanager to be accessed by customers. The registration method is similar to the drivermanager and driver of JDBC APIs.

The runtime interface is a key part of the Runtime API. The runtime interface provides a method for creating a rule session, which is used to run the rule. The Runtime API also provides access to all rule execution sets registered with the service provider ). The rule session interface defines the type of session used by the customer. The customer can choose to use a stateful session or stateless session based on the method of running the rule. Stateless sessions work like a stateless Session Bean. You can send a single input object or a column object to obtain the output object. A stateful session is useful when you need a dedicated session with the rule engine. The input object can be added to the session through the addobject () method. Multiple objects can be added to a session. You can use the updateobject () method to update existing objects in the dialog. As long as the session between the customer and the Rule Engine still exists, the objects in the session will not be lost.

The ruleexecutionsetmetadata interface allows you to query metadata of the rule execution set ). Metadata is provided to users through the rule session interface (rulesession interface.

2. Java Rule Engine API security issues

Rule Engine APIs separate Management APIs and runtime APIs to provide better granularity security control for these packages. The Rules Engine API does not provide an obvious security mechanism. It can be used together with the standard security API defined in the J2EE specification. Security can be provided by the following mechanisms, such as Java authentication and authorization Service (JAAS), Java encryption extension (JCE), Java Secure Socket Extension (JSSE), or other customized security APIs. JAAS allows you to define the permission limits for rule execution sets so that only authorized users can access them.

3. Exceptions and logs

The rule engine API defines javax. Rules. ruleexception as the root class of the Rule Engine exception level. All other exceptions inherit from this root class. All exceptions defined in the rule engine are controlled exceptions, so the tasks for capturing exceptions are handed over to the rule engine. The rule engine API does not provide a clear log mechanism, but it is recommended that Java logging API be used for the rule engine API.

JSR 94 provides a public standard API for the rule engine and provides guidance only for implementing the rule management API and Runtime API, there is no rule or action definition or language used to define rules, nor does it provide technical guidance for the rule engine to read or evaluate rules.

  Conclusion

The rule engine technology provides a solution for managing variable business logic. The rule engine can manage the business logic of the application layer and make the page flow of the presentation layer customizable. This provides a new choice for software architects to design large information systems. The Java rule engine will surely develop further after the Java Community develops standard specifications.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.