1. esper的安装:
在 http://esper.codehaus.org/esper/download/download.html 这里下载esper压缩包。解压缩之后获得文件夹 esper-4.x.x,在该文件夹根目录有 esper-4.x.x.jar,这就是我们需要用到的esper库,将其加入到项目中。值得注意的是,使用esper不仅仅需要这个jar文件,还需要esper所依赖的其他的库。我们还需要将 esper-4.x.x/esper/lib 文件夹内的4个jar文件同样加入项目,这样才能正常使用 esper。
2. 详细安装方法:
已经安装好esper的同学可以直接跳至第三步。由于本人刚刚学习Java,对于Java的对于第三方库的使用非常不了解。所以费了老半天劲才将esper引入项目,其实很简单。(1) 将esper-4.x.x.jar 文件拖入eclipse的项目中,选择“Copy File”。(2) 右击项目名 => Properties => Libraries => Add JARs => 选择 esper-4.x.x.jar => OK ,这样,esper就安装好了。(3) 同样的办法引入 esper-4.x.x/esper/lib 文件夹内的另外4个jar文件。之后,esper就可以使用了。
public class exampleMain {
public static class Tick {
String symbol;
Double price;
Date timeStamp;
public Tick(String s, double p, long t) {
symbol = s;
price = p;
timeStamp = new Date(t);
}
public double getPrice() {return price;}
public String getSymbol() {return symbol;}
public Date getTimeStamp() {return timeStamp;}
@Override
public String toString() {
return "Price: " + price.toString() + " time: " + timeStamp.toString();
}
}
private static Random generator = new Random();
public static void GenerateRandomTick(EPRuntime cepRT) {
double price = (double) generator.nextInt(10);
long timeStamp = System.currentTimeMillis();
String symbol = "AAPL";
Tick tick = new Tick(symbol, price, timeStamp);
System.out.println("Sending tick:" + tick);
cepRT.sendEvent(tick);
}
public static class CEPListener implements UpdateListener {
public void update(EventBean[] newData, EventBean[] oldData) {
System.out.println("Event received: " + newData[0].getUnderlying());
}
}
public static void main(String[] args) {
//The Configuration is meant only as an initialization-time object.
Configuration cepConfig = new Configuration();
cepConfig.addEventType(“StockTick”, Tick.class.getName());
EPServiceProvider cep = EPServiceProviderManager.getProvider(“myCEPEngine”, cepConfig);
EPRuntime cepRT = cep.getEPRuntime();
EPAdministrator cepAdm = cep.getEPAdministrator();
EPStatement cepStatement = cepAdm.createEPL("select * from " +
"StockTick(symbol='AAPL').win:length(2) " +
"having avg(price) > 6.0");
cepStatement.addListener(new CEPListener());
// We generate a few ticks...
for (int i = 0; i < 5; i++) {
GenerateRandomTick(cepRT);
}
}
}`
输出:
log4j: WARN No appenders could be found for logger (com.espertech.esper.epl.metric.MetricReportingPath). log4j:WARN Please initialize the log4j system properly. Sending tick:Price: 6.0 time: Tue Jul 21 01:11:15 CEST 2009 Sending tick:Price: 0.0 time: Tue Jul 21 01:11:15 CEST 2009 Sending tick:Price: 7.0 time: Tue Jul 21 01:11:15 CEST 2009 Sending tick:Price: 4.0 time: Tue Jul 21 01:11:15 CEST 2009 Sending tick:Price: 9.0 time: Tue Jul 21 01:11:15 CEST 2009 Event received: Price: 9.0 time: Tue Jul 21 01:11:15 CEST 2009