flink drools开发

 flink本身已有cep引擎,用户可以直接使用。本文介绍下flink drools集成开发,实现规则代码分离。

项目代码结构如下:

flink drools开发_第1张图片

pom maven配置:

 
        
          6.5.0.Final
    
    
    
        org.apache.flink
        flink-java
        1.7.2
    
    
        org.apache.flink
        flink-scala_2.11
        1.7.2
    
    
        org.apache.flink
        flink-streaming-java_2.11
        1.7.2
    
    
        org.apache.flink
        flink-clients_2.11
        1.7.2
    
    
        org.apache.flink
        flink-cep_2.11
        1.7.2
    
        
        
            org.drools
            drools-compiler
            ${drools.version}
        
        
        
            org.drools
            drools-core
            ${drools.version}
        
    

代码:

   StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

   AfterMatchSkipStrategy skipStrategy = AfterMatchSkipStrategy.skipPastLastEvent();
        DataStream input = env.fromElements(new Person("1",8),new Person("2",10),
                new Person("3",18),
                new Person("4",15),
                new Person("5",25));
        input.map(new RichMapFunction() {
            @Override
            public Person map(Person s) throws Exception {

                KieHelper kieHelper = new KieHelper();
//                kieHelper.addContent()
                kieHelper.kfs.write( new ClassPathResource( "rules/Sample.drl") );
                KieBase kbase = kieHelper.build();
                StatelessKieSession statelessKieSession = kbase.newStatelessKieSession();
                statelessKieSession.execute(s);
                return s;
            }
        }).print();

        env.execute("cep");
public class Person {
    public Person(){

    }
    public Person(String name , int age){
        this.name = name;
        this.age = age;
    }
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

规则:

package ruls

import com.wf.flink.data.Person;

rule "Hello World"
    when
       b:Person( age >= 18 );
    then
        System.out.println("==================person================"+ b.getAge() );
end

测试执行:

2> com.wf.flink.data.Person@156911
3> com.wf.flink.data.Person@1db8a45
4> com.wf.flink.data.Person@1f787a
==================person================18
1> com.wf.flink.data.Person@5a19ef
==================person================25
3> com.wf.flink.data.Person@92ff81

flink drools集成测试6.5版本本地,集群模式都可以正常运行。与drools7.23集成时本地可以执行,提交到集群时出现空指针异常暂时没有解决。

你可能感兴趣的:(flink)