下来是定义数据模型,Gora使用Apache Avro来定义数据的对象模型,avro可以方便的提供跟踪数对象的持久化状态与对象的持久化功能。定义数据模型还是比较简单的,它是以json格式来定义的,其中使用的PageView(src/main/avro/pageview.json)的定义格式如下:
- {
- "type": "record",
- "name": "Pageview",
- "namespace": "org.apache.gora.tutorial.log.generated",
- "fields" : [
- {"name": "url", "type": "string"},
- {"name": "timestamp", "type": "long"},
- {"name": "ip", "type": "string"},
- {"name": "httpMethod", "type": "string"},
- {"name": "httpStatusCode", "type": "int"},
- {"name": "responseSize", "type": "int"},
- {"name": "referrer", "type": "string"},
- {"name": "userAgent", "type": "string"}
- ]
- }
我们可以看到,其中的数据类型是record,name是生成的类的名称,而namespace是对应java中package的名字,而fields中定义的字段的名称与类型。
下来是对定义好的数据模型进行编译,自动生成相应的代码,命令如下
- $ bin/gora compile
- $ Usage: SpecificCompiler <schema file> <output dir>
- $ bin/gora compile gora-tutorial/src/main/avro/pageview.json gora-tutorial/src/main/java/
编译以后生成文件 gora-tutorial/src/main/java/org/apache/gora/tutorial/log/generated/Pageview.java
这里Gora的解析器扩展了Avro的SpecificCompiler方法,因为生成的对象模型在扩展自Gora自己的Persistent接口,而Persistent这个接口定义了对象的持久化,对象状态的跟踪等方法。下面是部分Pageview.java的代码
- public class Pageview extends PersistentBase {
- private Utf8 url;
- private long timestamp;
- private Utf8 ip;
- private Utf8 httpMethod;
- private int httpStatusCode;
- private int responseSize;
- private Utf8 referrer;
- private Utf8 userAgent;
- ...
- public static final Schema _SCHEMA = Schema.parse("{\"type\":\"record\", ... ");
- public static enum Field {
- URL(0,"url"),
- TIMESTAMP(1,"timestamp"),
- IP(2,"ip"),
- HTTP_METHOD(3,"httpMethod"),
- HTTP_STATUS_CODE(4,"httpStatusCode"),
- RESPONSE_SIZE(5,"responseSize"),
- REFERRER(6,"referrer"),
- USER_AGENT(7,"userAgent"),
- ;
- private int index;
- private String name;
- Field(int index, String name) {this.index=index;this.name=name;}
- public int getIndex() {return index;}
- public String getName() {return name;}
- public String toString() {return name;}
- };
- public static final String[] _ALL_FIELDS = {"url","timestamp","ip","httpMethod"
- ,"httpStatusCode","responseSize","referrer","userAgent",};
- ...
- }
