---
title: "Esper入门例子（二）"
author: "Josh_Persistence"
date: "2014-03-19T13:17:22Z"
tags: ["Esper"]
categories: ["行业应用"]
slug: "esper"
draft: false
lastmod: "2014-03-19T13:42:27Z"
id: 2033466
url: "https://josh-persistence.iteye.com/blog/2033466"
---

***Esper入门例子***

      说到Esper，不得不说一下CEP。CEP即Complex Event Process，中文意思就是“复杂事件处理”。听起来好像很复杂，实际上就是基于事件流进行数据处理，把要分析的数据抽象成事件，然后将数据发送到 CEP引擎，引擎就会根据事件的输入和最初注册的处理模型，得到事件处理结果。

     

       ***CEP是一种标准，Esper只是对这个标准的一种开源实现。***除了Esper，很多大公司也有类似的商业软件实现，比如IBM，Sybase等等。CEP的一个重要特点就是他是一个内存计算工具和类SQL语句。内存计算可以说是一把双刃剑。好处自不必说，一个字：快！坏处也显而易见，数据有丢失的风险，而且还有容量的限制（实时计算其实并不受制于内存大小，而是得看如何对实时进行定义，也就是具体的业务来决定了）。所以如果业务不能容忍数据丢 失，那么高可用方案就必须做好，不过Esper的高可用很不好做，后面我将会说到。

       CEP的类SQL语句，可以理解为处理模型的定义与描述。这是运行在CEP引擎中的特殊语句，之所以叫他类SQL，是因为它和SQL确实很像，除了 select，insert，delete，update，而且也有avg，count等函数。所以对于会SQL的人来说，他的语法结构大致还是能猜出一 二的。在Esper中，这个句子叫做EPL，即Event Process Language。作为Esper的核心内容，对于它的讲解有三四百页的英文文档，所以之后我会慢慢向大家细细说明的。

     下面的场景是计算3个苹果的平均价格。

 

```
    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();  
            String epl = "select avg(price) from " + product + ".win:length_batch(3)";  
      
            EPStatement state = admin.createEPL(epl);  
            state.addListener(new AppleListener());  
      
            EPRuntime runtime = epService.getEPRuntime();  
      
            Apple apple1 = new Apple();  
            apple1.setId(1);  
            apple1.setPrice(5);  
            runtime.sendEvent(apple1);  
      
            Apple apple2 = new Apple();  
            apple2.setId(2);  
            apple2.setPrice(2);  
            runtime.sendEvent(apple2);  
      
            Apple apple3 = new Apple();  
            apple3.setId(3);  
            apple3.setPrice(5);  
            runtime.sendEvent(apple3);  
        }  
    }  
```

 

***下一讲将会讲解Esper的事件。***