这个框架的核心原理是通过定义和实现注解来达到简化Thrift文件的目的,使得在开发时定义的POJO和Interface都能够和普通的java文件一致;
我们直接看例子,我们定义一个实体类,可以简化写法是:
@ThriftStruct
public class ThirdPartyCollection {
public final long id; // required
public final String date; // optional
@ThriftConstructor
public ThirdPartyCollection(long id, String date) {
this.id = id;
this.date = date;
}
@ThriftField(1)
public long getId() {
return id;
}
@ThriftField(2)
public String getDate() {
return date;
}
这要比直接使用thrift IDL生成的java代码简单非常多的倍数;定义service写法如下:
@ThriftService("ThirdPartyCollectionService")
public interface ThirdPartyCollectionService {
@ThriftMethod
public ThirdPartyCollection save(@ThriftField(name = "collection") ThirdPartyCollection collection) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException;
@ThriftMethod
public ThirdPartyCollection update(@ThriftField(name = "collection") ThirdPartyCollection collection);
@ThriftMethod
public List<ThirdPartyCollection> getAll();
}
写法需要在类和方法以及方法参数增加注解即可。
同时,启动服务和client调用的代码也有所变动:
同时,启动服务和client调用的代码也有所变动:
public static void main(String[] args) throws IOException, InterruptedException {
ThriftServiceProcessor processor = new ThriftServiceProcessor(
new ThriftCodecManager(),
ImmutableList.<ThriftEventHandler>of(),
new ThirdPartyCollectionServiceImpl()
);
taskWorkerExecutor = newFixedThreadPool(1);
ThriftServerDef serverDef = ThriftServerDef.newBuilder()
.listen(8899)
.withProcessor(processor)
.using(taskWorkerExecutor)
.build();
bossExecutor = newCachedThreadPool();
ioWorkerExecutor = newCachedThreadPool();
NettyServerConfig serverConfig = NettyServerConfig.newBuilder()
.setBossThreadExecutor(bossExecutor)
.setWorkerThreadExecutor(ioWorkerExecutor)
.build();
server = new ThriftServer(serverConfig, serverDef);
server.start();
}
Client端调用代码:public static void main(String[] args) throws ExecutionException, InterruptedException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ThriftClientManager clientManager = new ThriftClientManager();
FramedClientConnector connector = new FramedClientConnector(new InetSocketAddress("localhost",8899));
ThirdPartyCollectionService scribe = clientManager.createClient(connector, ThirdPartyCollectionService.class).get();
scribe.getAll();
com.qiyi.thrift.test.core.ThirdPartyCollection collection =
new com.qiyi.thrift.test.core.ThirdPartyCollection(1001, "2014-08-29");
scribe.save(collection);
}
没有评论:
发表评论