Esper 事件之事件上下文 - Context (五)

Esper 事件之事件上下文 - Context 

 

Context是Esper中的事件的上下文,从Context中,你可以获取事件的相关信息。我们也可吧Context理解成一个框,把不同的事件按照框的规则框起来,并且有可能有多个框,而框与框之间不会互相影响。

 

1.Context基本语法

语法结构如下:

    create context context_name partition [by] event_property [and event_property [and ...]] from stream_def   
    [, event_property [...] from stream_def] [, ...]  

说明:
context_name为context的名字,并且唯一。如果重复,会说明已存在。

扫描二维码关注公众号,回复: 393481 查看本文章

event_property为事件的属性名,多个属性名之间用and连接,也可以用逗号连接。

stream_def为事件流的定义,简单的定义可以是一个事件的名称,比如之前定义了一个Map结构的事件为User,那么这里就可以写User。复杂的流定义后面会说到

举个例子:

    create context NewUser partition by id and name from User  
    // id和name是User的属性  

如果context包含多个流,例子如下:

    create context Person partition by sid from Student, tid from Teacher  
    // sid是Student的属性,tid是Teacher的属性  

多个流一定要注意,每个流的中用于context的属性的数量要一样,数据类型也要一致。比如下面这几个就是错误的:

    create context Person partition by sid from Student, tname from Teacher  
    // 错误:sid是int,tname是String,数据类型不一致  
      
    create context Person partition by sid from Student, tid,tname from Teacher  
    // 错误:Student有一个属性,Teacher有两个属性,属性数量不一致  
      
    create context Person partition by sid,sname from Student, tname,tid from Teacher  
    // 错误:sid对应tname,sname对应tid,并且sname和tname是String,sid和tid是int,属性数量一样,但是对应的数据类型不一致  

实际上可以对进入context的事件增加过滤条件,不符合条件的就被过滤掉,就像下面这样:

    create context Person partition by sid from Student(age > 20)  
    // age大于20的Student事件才能建立或者进入context  

看了这么多,可能只是知道context的一些基本定义方法,但是不知道什么意思。其实很简单,partition by后面的属性,就是作为context的一个约束,比如说id,如果id相等的则进入同一个context里,如果id不同,那就新建一个 context。好比根据id分组,id相同的会被分到一个组里,不同的会新建一个组并等待相同的进入。

       如果parition by后面跟着同一个流的两个属性,那么必须两个属性值一样才能进入context。比如说A事件id=1,name=a,那么会以1和a两个值建立 context,有点像数据库里的联合主键。然后B事件id=1,name=b,则又会新建一个context。接着C事件id=1,name=a,那么 会进入A事件建立的context。

       如果partition by后面跟着两个流的一个属性,那么两个属性值一样才能进入context。比如说Student事件sid=1,那么会新建一个context,然后来 了个Teacher事件tid=1,则会进入sid=1的那个context。多个流也一样,不用关心是什么事件,只用关心事件的属性值一样即可进入同一 个context。

要是说了这么多还是不懂,可以看看下面要讲的context自带属性也许就能明白一些了。

2. Built-In Context Properties

Context本身自带一些属性,最关键的是可以查看所创建的context的标识,并帮助我们理解context的语法。

如上所示,name表示context的名称,这个是不会变的。id是每个context的唯一标识,从0开始。key1和keyN表示context定义时所选择的属性的值,1和N表示属性的位置。例如:

    EPL: create context Person partition by sid, sname from Student  
    // key1为sid,key2为sname  

 

为了说明对这几个属性的应用,看一个比较完整的例子。

    import com.espertech.esper.client.EPAdministrator;  
    import com.espertech.esper.client.EPRuntime;  
    import com.espertech.esper.client.EPServiceProvider;  
    import com.espertech.esper.client.EPServiceProviderManager;  
    import com.espertech.esper.client.EPStatement;  
    import com.espertech.esper.client.EventBean;  
    import com.espertech.esper.client.UpdateListener;  
      
    class ESB  
    {  
      
        private int id;  
        private int price;  
      
        public int getId()  
        {  
            return id;  
        }  
      
        public void setId(int id)  
        {  
            this.id = id;  
        }  
      
        public int getPrice()  
        {  
            return price;  
        }  
      
        public void setPrice(int price)  
        {  
            this.price = price;  
        }  
      
    }  
      
    class ContextPropertiesListener2 implements UpdateListener  
    {  
      
        public void update(EventBean[] newEvents, EventBean[] oldEvents)  
        {  
            if (newEvents != null)  
            {  
                EventBean event = newEvents[0];  
                System.out.println("context.name " + event.get("name") + ", context.id " + event.get("id") + ", context.key1 " + event.get("key1")  
                        + ", context.key2 " + event.get("key2"));  
            }  
        }  
    }  
      
    public class ContextPropertiesTest2  
    {  
        public static void main(String[] args)  
        {  
            EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider();  
            EPAdministrator admin = epService.getEPAdministrator();  
            EPRuntime runtime = epService.getEPRuntime();  
      
            String esb = ESB.class.getName();  
            // 创建context  
            String epl1 = "create context esbtest partition by id,price from " + esb;  
            // context.id针对不同的esb的id,price建立一个context,如果事件的id和price相同,则context.id也相同,即表明事件进入了同一个context  
            String epl2 = "context esbtest select context.id,context.name,context.key1,context.key2 from " + esb;  
      
            admin.createEPL(epl1);  
            EPStatement state = admin.createEPL(epl2);  
            state.addListener(new ContextPropertiesListener2());  
      
            ESB e1 = new ESB();  
            e1.setId(1);  
            e1.setPrice(20);  
            System.out.println("sendEvent: id=1, price=20");  
            runtime.sendEvent(e1);  
      
      
            ESB e2 = new ESB();  
            e2.setId(2);  
            e2.setPrice(30);  
            System.out.println("sendEvent: id=2, price=30");  
            runtime.sendEvent(e2);  
      
            ESB e3 = new ESB();  
            e3.setId(1);  
            e3.setPrice(20);  
            System.out.println("sendEvent: id=1, price=20");  
            runtime.sendEvent(e3);  
      
            ESB e4 = new ESB();  
            e4.setId(4);  
            e4.setPrice(20);  
            System.out.println("sendEvent: id=4, price=20");  
            runtime.sendEvent(e4);  
        }  
    }  

执行结果:

    sendEvent: id=1, price=20  
    context.name esbtest, context.id 0, context.key1 1, context.key2 20  
    sendEvent: id=2, price=30  
    context.name esbtest, context.id 1, context.key1 2, context.key2 30  
    sendEvent: id=1, price=20  
    context.name esbtest, context.id 0, context.key1 1, context.key2 20  
    sendEvent: id=4, price=20  
    context.name esbtest, context.id 2, context.key1 4, context.key2 20  

这个例子说得比较明白,针对不同的id和price,都会新建一个context,并且context.id会从0开始增加作为其标识。如果id和 price一样,事件就会进入之前已经存在的context,所以e3这个事件就会和e1一样存在于context.id=0的context里面。

      对于epl2这个句子,意思是在esbtest这个context限制下进行事件的计算,不过这个句子很简单,可以说没有什么计算,事件进入后就显示出来 了。实际上写成什么样都可以,但是必须以context xxx开头(xxx表示context定义时的名字),比如说:

// context定义  
create context esbtest2 partition by id from ESB  
  
// 每当5个id相同的ESB事件进入时,统计price的总和  
context esbtest select sum(price) from ESB.win:length_batch(5)  
  
// 根据不同的id,统计3秒内进入的事件的平均price,且price必须大于10  
context esbtest select avg(price) from ESB(price>10).win:time(3 sec) 

   也许你会发现为什么EPL的句子都会带有".win:length"或者".win:time",那是因为我们要计算的都是一堆事件,所以必须用一定条件才能 把事件聚集起来。当然并不是一个事件没法计算,只不过更多情况下计算都是以多个事件为基础的。关于这一点,学习到后面就会有更多的接触。

3. Hash Context

       前面介绍的Context语法是以事件属性来定义的,Esper提供了以Hash值为标准定义Context,通俗一点说就是提供事件属性参与hash值的计算,计算的值再对某个值(这是什么)是同余的则进入到同一个context中。详细语法如下:

    create context context_name coalesce [by]  
    hash_func_name(hash_func_param) from stream_def  
    [, hash_func_name(hash_func_param) from stream_def ]  
    [, ...]  
    granularity granularity_value  
    [preallocate]   

a). hash_func_name为hash函数的名称,Esper提供了CRC32或者使用Java的hashcode函数来计算hash值,分别为consistent_hash_crc32和hash_code。你也可以自己定义hash函数,不过这需要配置。

b). hash_func_param为参与计算的属性列表,比如之前的sid或者tname什么的。

c). stream_def就是事件类型,可以一个可以多个。不同于前面的Context语法要求,Hash Context不管有多个少属性作为基础来计算hash值,hash值都只有一个,并且为int型。所以就不用关心这些属性的个数以及数据类型了。

d). granularity是必选参数,表示为最多能创建多少个context

e). granularity_value就是那个用于取余的“某个值”,因为Esper为了防止内存溢出,就想出了取余这种办法来限制context创建的数 量。也就是说context.id=hash_func_name(hash_func_param)  % granularity_value。

f). preallocate是一个可选参数,如果使用它,那么Esper会预分配空间来创建granularity_value数量的context。比如说 granularity_value为1024,那么Esper会预创建1024个context。内存不大的话不建议使用这个参数。

Hash Context同样可以过滤事件,举个完整的例子:

// 以java的hashcode方法计算sid的值(sid必须大于5),以CRC32算法计算tid的值,然后对10取余后的值来建立context  
create context HashPerson coalesce by hash_code(sid) from Student(sid>5), consistent_hash_crc32(tid) from Teacher granularity 10 

Hash Context也有Built-In Context Properties,只不过只有context.id和context.name了。用法和前面说的一样,这里就不列举了。

小贴士:

1.如果用于hash计算的属性比较多,那么就不建议使用CRC32算法了,因为他会把这些属性值先序列化字节数组以后才能计算hash值。hashcode方法相对它能快很多。

2.如果使用preallocate参数,建议granularity_value不要超过1000

3.如果granularity_value超过65536,引擎查找context会比较费劲,进而影响计算速度

4. Category Context

Category Context相对之前的两类context要简单许多,也更容易理解。语法说明如下:

    create context context_name  
    group [by] group_expression as category_label  
    [, group [by] group_expression as category_label]  
    [, ...]  
    from stream_def  

group_expression表示分组策略的表达式,category_label为策略定义一个名字,一个context可以有多个策略同时存在,但是特殊的是之能有一个stream_def。例如:

    create context CategoryByTemp  
    group temp < 5 as cold, group temp between 5 and 85 as normal, group temp > 85 as large  
    from Temperature  

Category Context也有它自带的属性。

label指明进入的事件所处的group是什么。完整例子如下:

    import com.espertech.esper.client.EPAdministrator;  
    import com.espertech.esper.client.EPRuntime;  
    import com.espertech.esper.client.EPServiceProvider;  
    import com.espertech.esper.client.EPServiceProviderManager;  
    import com.espertech.esper.client.EPStatement;  
    import com.espertech.esper.client.EventBean;  
    import com.espertech.esper.client.UpdateListener;  
      
    class ESB3  
    {  
        private int id;  
        private int price;  
      
        public int getId()  
        {  
            return id;  
        }  
      
        public void setId(int id)  
        {  
            this.id = id;  
        }  
      
        public int getPrice()  
        {  
            return price;  
        }  
      
        public void setPrice(int price)  
        {  
            this.price = price;  
        }  
    }  
      
    class ContextPropertiesListener4 implements UpdateListener  
    {  
        public void update(EventBean[] newEvents, EventBean[] oldEvents)  
        {  
            if (newEvents != null)  
            {  
                EventBean event = newEvents[0];  
                System.out.println("context.name " + event.get("name") + ", context.id " + event.get("id") + ", context.label " + event.get("label"));  
            }  
        }  
    }  
      
    public class ContextPropertiesTest4  
    {  
        public static void main(String[] args)  
        {  
            EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider();  
            EPAdministrator admin = epService.getEPAdministrator();  
            EPRuntime runtime = epService.getEPRuntime();  
      
            String esb = ESB3.class.getName();  
            String epl1 = "create context esbtest group by id<0 as low, group by id>0 and id<10 as middle,group by id>10 as high from " + esb;  
            String epl2 = "context esbtest select context.id,context.name,context.label, price from " + esb;  
      
            admin.createEPL(epl1);  
            EPStatement state = admin.createEPL(epl2);  
            state.addListener(new ContextPropertiesListener4());  
      
            ESB3 e1 = new ESB3();  
            e1.setId(1);  
            e1.setPrice(20);  
            System.out.println("sendEvent: id=1, price=20");  
            runtime.sendEvent(e1);  
      
      
            ESB3 e2 = new ESB3();  
            e2.setId(0);  
            e2.setPrice(30);  
            System.out.println("sendEvent: id=0, price=30");  
            runtime.sendEvent(e2);  
      
            ESB3 e3 = new ESB3();  
            e3.setId(11);  
            e3.setPrice(20);  
            System.out.println("sendEvent: id=11, price=20");  
            runtime.sendEvent(e3);  
      
            ESB3 e4 = new ESB3();  
            e4.setId(-1);  
            e4.setPrice(40);  
            System.out.println("sendEvent: id=-1, price=40");  
            runtime.sendEvent(e4);  
        }  
    }  

 输出结果为:

    sendEvent: id=1, price=20  
    context.name esbtest, context.id 1, context.label middle  
    sendEvent: id=0, price=30  
    sendEvent: id=11, price=20  
    context.name esbtest, context.id 2, context.label high  
    sendEvent: id=-1, price=40  
    context.name esbtest, context.id 0, context.label low  

可以发现,id=0的事件,并没有触发监听器,那是因为context里的三个category没有包含id=0的情况,所以这个事件就被排除掉了。

5. Non-Overlapping Context

这类Context有个特点,是由开始和结束两个条件构成context。语法如下:

create context context_name start start_condition end end_condition  


       这个context有两个条件做限制,形成一个约束范围。当开始条件和结束条件都没被触发时,引擎会观察事件的进入是否会触发开始条件。如果开始条件被触 发了,那么就新建一个context,并且观察结束条件是否被触发。如果结束条件被触发,那么context结束,引擎继续观察开始条件何时被触发。所以 说这类Context的另一个特点是,要么context存在并且只有一个,要么条件都没被触发,也就一个context都没有了。

start_condition和end_condition可以是时间,或者是事件类型。比如说:

    create context NineToFive start (0, 9, *, *, *) end (0, 17, *, *, *)  
    //  9点到17点此context才可用(以引擎的时间为准)。如果事件进入的事件不在此范围内,则不受该context影响  

 一个完整的例子,以某类事件开始,以某类事件结束

    import com.espertech.esper.client.EPAdministrator;  
    import com.espertech.esper.client.EPRuntime;  
    import com.espertech.esper.client.EPServiceProvider;  
    import com.espertech.esper.client.EPServiceProviderManager;  
    import com.espertech.esper.client.EPStatement;  
    import com.espertech.esper.client.EventBean;  
    import com.espertech.esper.client.UpdateListener;  
      
    class StartEvent  
    {  
    }  
      
    class EndEvent  
    {  
    }  
      
    class OtherEvent  
    {  
        private int id;  
      
        public int getId()  
        {  
            return id;  
        }  
      
        public void setId(int id)  
        {  
            this.id = id;  
        }  
    }  
      
    class NoOverLappingContextTest3 implements UpdateListener  
    {  
      
        public void update(EventBean[] newEvents, EventBean[] oldEvents)  
        {  
            if (newEvents != null)  
            {  
                EventBean event = newEvents[0];  
                System.out.println("Class:" + event.getUnderlying().getClass().getName() + ", id:" + event.get("id"));  
            }  
        }  
    }  
      
    public class NoOverLappingContextTest  
    {  
        public static void main(String[] args)  
        {  
            EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider();  
            EPAdministrator admin = epService.getEPAdministrator();  
            EPRuntime runtime = epService.getEPRuntime();  
      
            String start = StartEvent.class.getName();  
            String end = EndEvent.class.getName();  
            String other = OtherEvent.class.getName();  
            // 以StartEvent事件作为开始条件,EndEvent事件作为结束条件  
            String epl1 = "create context NoOverLapping start " + start + " end " + end;  
            String epl2 = "context NoOverLapping select * from " + other;  
      
            admin.createEPL(epl1);  
            EPStatement state = admin.createEPL(epl2);  
            state.addListener(new NoOverLappingContextTest3());  
      
            StartEvent s = new StartEvent();  
            System.out.println("sendEvent: StartEvent");  
            runtime.sendEvent(s);  
      
            OtherEvent o = new OtherEvent();  
            o.setId(2);  
            System.out.println("sendEvent: OtherEvent");  
            runtime.sendEvent(o);  
      
            EndEvent e = new EndEvent();  
            System.out.println("sendEvent: EndEvent");  
            runtime.sendEvent(e);  
      
            OtherEvent o2 = new OtherEvent();  
            o2.setId(4);  
            System.out.println("sendEvent: OtherEvent");  
            runtime.sendEvent(o2);  
        }  
    }  

执行结果:

sendEvent: StartEvent  
sendEvent: OtherEvent  
Class:blog.OtherEvent, id:2  
sendEvent: EndEvent  
sendEvent: OtherEvent 

由此可以看出,在NoOverLapping这个Context下监控OtherEvent,必须是在StartEvent被触发才能监控到,所以在EndEvent发送后,再发送一个OtherEvent是不会触发Listener的。

6. OverLapping

OverLapping和NoOverLapping一样都有两个条件限制,但是区别在于OverLapping的初始条件可以被触发多次,并且只要被触发就会新建一个context,但是当终结条件被触发时,之前建立的所有context都会被销毁。他的语法也很简单:

create context context_name initiated [by] initiating_condition terminated [by] terminating_condition 

initiating_condition和terminating_condition可以为事件类型,事件或者别的条件表达式。下面给出了一个完整的例子。

    import com.espertech.esper.client.EPAdministrator;  
    import com.espertech.esper.client.EPRuntime;  
    import com.espertech.esper.client.EPServiceProvider;  
    import com.espertech.esper.client.EPServiceProviderManager;  
    import com.espertech.esper.client.EPStatement;  
    import com.espertech.esper.client.EventBean;  
    import com.espertech.esper.client.UpdateListener;  
      
    class InitialEvent{}  
      
    class TerminateEvent{}  
      
    class SomeEvent  
    {  
        private int id;  
      
        public int getId()  
        {  
            return id;  
        }  
      
        public void setId(int id)  
        {  
            this.id = id;  
        }  
    }  
      
    class OverLappingContextListener implements UpdateListener  
    {  
      
        public void update(EventBean[] newEvents, EventBean[] oldEvents)  
        {  
            if (newEvents != null)  
            {  
                EventBean event = newEvents[0];  
                System.out.println("context.id:" + event.get("id") + ", id:" + event.get("id"));  
            }  
        }  
    }  
      
    class OverLappingContextListener2 implements UpdateListener  
    {  
      
        public void update(EventBean[] newEvents, EventBean[] oldEvents)  
        {  
            if (newEvents != null)  
            {  
                EventBean event = newEvents[0];  
                System.out.println("Class:" + event.getUnderlying().getClass().getName() + ", id:" + event.get("id"));  
            }  
        }  
    }  
      
    public class OverLappingContextTest  
    {  
        public static void main(String[] args)  
        {  
            EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider();  
            EPAdministrator admin = epService.getEPAdministrator();  
            EPRuntime runtime = epService.getEPRuntime();  
      
            String initial = InitialEvent.class.getName();  
            String terminate = TerminateEvent.class.getName();  
            String some = SomeEvent.class.getName();  
            // 以InitialEvent事件作为初始事件,TerminateEvent事件作为终结事件  
            String epl1 = "create context OverLapping initiated " + initial + " terminated " + terminate;  
            String epl2 = "context OverLapping select context.id from " + initial;  
            String epl3 = "context OverLapping select * from " + some;  
      
            admin.createEPL(epl1);  
            EPStatement state = admin.createEPL(epl2);  
            state.addListener(new OverLappingContextListener());  
            EPStatement state1 = admin.createEPL(epl3);  
            state1.addListener(new OverLappingContextListener2());  
      
            InitialEvent i = new InitialEvent();  
            System.out.println("sendEvent: InitialEvent");  
            runtime.sendEvent(i);  
      
            SomeEvent s = new SomeEvent();  
            s.setId(2);  
            System.out.println("sendEvent: SomeEvent");  
            runtime.sendEvent(s);  
      
            InitialEvent i2 = new InitialEvent();  
            System.out.println("sendEvent: InitialEvent");  
            runtime.sendEvent(i2);  
      
            TerminateEvent t = new TerminateEvent();  
            System.out.println("sendEvent: TerminateEvent");  
            runtime.sendEvent(t);  
      
            SomeEvent s2 = new SomeEvent();  
            s2.setId(4);  
            System.out.println("sendEvent: SomeEvent");  
            runtime.sendEvent(s2);  
        }  
    }  
    sendEvent: InitialEvent  
    context.id:0, id:0  
    sendEvent: SomeEvent  
    Class:blog.SomeEvent, id:2  
    sendEvent: InitialEvent  
    context.id:1, id:1  
    context.id:0, id:0  
    sendEvent: TerminateEvent  
    sendEvent: SomeEvent  

从结果可以看得出来,每发送一个InitialEvent,都会新建一个context,以至于context.id=0和1。并且当发送TerminateEvent后,再发送SomeEvent监听器也不会被触发了。

另外,context.id是每一种Context都会有的自带属性,而且针对OverLapping,还增加了startTime和endTime两种属性,表明context的开始时间和结束时间。

7. Context Condition

Context Condition主要包含Filter,Pattern,Crontab以及Time Period

A). Filter主要就是对属性值的过滤,比如:

create context NewUser partition by id from User(id > 10)  

B). Pattern是复杂事件流的代表,比如说“A事件到达后跟着B事件到达”这是一个完整的Pattern。Pattern是Esper里面很特别的东西,并且用它描述复杂的事件流是最合适不过的了。这里暂且不展开说,后面会有专门好几篇来讲解Pattern。

C). Crontab是定时任务,主要用于NoOverLapping,就像前面提到的(0, 9, *, *, *),括号里的五项代表分,时,天,月,年。关于这个后面也会有讲解。

D). Time Period在这里只有一种表达式,就是after time_period_expression。例如:after 1 minute,after 5 sec。结合Context的例子如下:

// 以0秒为时间初始点,新建一个context,于10秒后开始,1分钟后结束。下一个context从1分20秒开始  
create context NonOverlap10SecFor1Min start after 10 seconds end after 1 minute 

8. Context Nesting

Context也可以嵌套,意义就是多个Context联合在一起组成一个大的Context,以满足复杂的限制需求。语法结构:

    create context context_name  
    context nested_context_name [as] nested_context_definition ,  
    context nested_context_name [as] nested_context_definition [, ...]  

举个例子:

    create context NineToFiveSegmented  
    context NineToFive start (0, 9, *, *, *) end (0, 17, *, *, *),  
    context SegmentedByUser partition by userId from User  

应用和普通的Context没区别,在此就不举例了。另外针对嵌套Context,其自带的属性使用方式会有些变化。比如针对上面这个,若想查看NineToFive的startTime和SegmentedByUser的第一个属性值,要按照下面这样写:

    context NineToFiveSegmented select  
     context.NineToFive.startTime,  
     context.SegmentedByUser.key1  
     from User  

 


9. Output When Context Partition Ends

当Context销毁时,如果你想同时查看此时Context里的东西,那么Esper提供了一种办法来输出其内容。例如:

    create context OverLapping initiated InitialEvent terminated TerminateEvent  
    context OverLapping select * from User output snapshot when terminated  

 

那么当终结事件发送到引擎后,会立刻输出OverLapping的快照。

如果你想以固定的频率查看Context的内容,Esper也支持。例如

context OverLapping select * from User output snapshot every 2 minute // 每两分钟输出OverLapping的事件  

关于output表达式,后面也会有详解。

10、Group by和Context的区别:

 

       其实如果只是很简单的用Context,没太大区别,无非是在Context下select可以不包含group by修饰的属性。

      但是Group by明显没有Context强大,很多复杂的分组Group by是没法做到的。不过在能达到同样效果的情况下,我还是建议使用Group by,毕竟Context的名字是不能重复的,而且在高并发的情况下Context会短时间锁住。后面的博客也会涉及这方面的内容。

猜你喜欢

转载自josh-persistence.iteye.com/blog/2034480