esper(複雜事件處理引擎)簡介
阿新 • • 發佈:2019-01-05
Esper是一個複雜事件處理引擎,用於對同一型別的多個物件進行統計分析。
要統計的多個事件(一個事件通常對應著一個物件)會儲存在一個佇列中,這裡叫它EQueue。
獲得
<dependency>
<groupId>com.espertech</groupId>
<artifactId>esper</artifactId>
<version>4.9.0</version>
</dependency>
我的入門DEMO在 點選開啟我的GitHub
EPL
EPL,Event Process Language,事件處理語言。類似於SQL,描述了esper要分析的內容。
詳見該分類下的其他博文。
事件型別
javaPojo
可以傳送javaPojo,也可以傳送map。
傳送javaPojo時,直接建立epl = "select avg(price) from " + javaPojo.class.getName() + ".win:length_batch(2)";即可。
map
傳送map時,可以登錄檔的型別,見下:
//傳送map時,可以登錄檔的型別 // Person定義 Map<String, Object> personTable = new HashMap<String, Object>(); personTable.put("name", String.class); personTable.put("age", Integer.class); // 註冊Person到Esper admin.getConfiguration().addEventType("personEventTypeName",personTable);
傳送map時,也可以通過epl語句建立。
//傳送map時,也可以通過epl語句建立。
String createEpl="create schema appTable as (`id` int, `price` int, `color` string)";
admin.createEPL(createEpl);
注意:如果把schema看成一張表,我們傳送的map中列數少了不報錯,列數多了不報錯(esper只用能匹配得上的元素),列名對應的資料型別不匹配也不報錯(esper不會幫你轉換)。例子
package test; 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 Apple { 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 AppleListener implements UpdateListener { public void update(EventBean[] newEvents, EventBean[] oldEvents) { if (newEvents != null) { Double avg = (Double) newEvents[0].get("avg(price)"); System.out.println("Apple's average price is " + avg); } } } public class Test { public static void main(String[] args) throws InterruptedException { EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(); EPAdministrator admin = epService.getEPAdministrator(); String product = Apple.class.getName(); //統計視窗限定為:事件個數為2。每攢夠2個就計算一次,然後清空佇列。 String epl = "select avg(price) from " + product + ".win:length_batch(2)"; EPStatement state = admin.createEPL(epl); state.addListener(new AppleListener()); EPRuntime runtime = epService.getEPRuntime(); Apple apple1 = new Apple(); apple1.setPrice(5); runtime.sendEvent(apple1); Apple apple2 = new Apple(); apple2.setPrice(2); runtime.sendEvent(apple2); Apple apple3 = new Apple(); apple3.setPrice(5); runtime.sendEvent(apple3); Apple apple4 = new Apple(); apple4.setPrice(7); runtime.sendEvent(apple4); } } /**Apple's average price is 3.5 Apple's average price is 6.0 */