什么是Kryo
Kryo 是一個(gè)快速高效的Java對(duì)象圖形序列化框架,主要特點(diǎn)是性能震蒋、高效和易用茸塞。該項(xiàng)目用來序列化對(duì)象到文件、數(shù)據(jù)庫或者網(wǎng)絡(luò)查剖。
Kryo同其他序列化框架的對(duì)比(Java比較流行的序列化框架)
Kryo钾虐, 優(yōu)點(diǎn):速度快,序列化后體積兴褡效扫;缺點(diǎn):跨語言支持較復(fù)雜
Hessian,優(yōu)點(diǎn):默認(rèn)支持跨語言直砂;缺點(diǎn):較慢
Protostuff 菌仁,優(yōu)點(diǎn):速度快,基于protobuf静暂;缺點(diǎn):需靜態(tài)編譯
什么是KryoCocoa
其實(shí)KryoCocoa就是Java中Kryo序列化框架的Objective-C版济丘,是為了兼容Kryo和基本的Java數(shù)據(jù)類型的。
這里是KryoCocoa的地址:https://github.com/Feuerwerk/kryococoa
基本使用
一籍嘹、將對(duì)象序列化后寫入某個(gè)文件中
假如有以下實(shí)體類:
@interfaceClassA:NSObject@property(assign,nonatomic) SInt32 uid;@property(copy,nonatomic)NSString*name;@end
將該實(shí)體類序列化后寫入到某個(gè)路徑下的某個(gè)文件
ClassA *a = [[ClassA alloc] init];
a.uid=1;
a.name=@"lisi";NSOutputStream*outputStream = [NSOutputStreamoutputStreamToFileAtPath:filePath append:NO];
KryoOutput *output = [[KryoOutput alloc] initWithStream:outputStream];
[k writeObject:a to:output];
[output close];
二闪盔、讀取某個(gè)文件反序列化成一個(gè)對(duì)象
NSInputStream*inputStream = [NSInputStreaminputStreamWithFileAtPath:filePath];
KryoInput *input = [[KryoInput alloc] initWithInput:inputStream];
ClassA *a = [k readObject:input ofClass:[ClassA class]];
[input close];NSLog(@"%d %@", a.uid,a.name);
序列化對(duì)象后通過Socket與Java后臺(tái)交互
假設(shè)有一個(gè)這樣的java實(shí)體類
packagecom.test.web.socket.modules.user.svo;publicclassTestSVO{privateLong uid;privateInteger status;publicLonggetUid(){returnuid;
}publicvoidsetUid(Long uid){this.uid = uid;
}publicIntegergetStatus(){returnstatus;
}publicvoidsetStatus(Integer status){this.status = status;
}
}
我們?cè)赬code中應(yīng)該這樣定義
#import#import"SerializationAnnotation.h"#import"JInteger.h"#import"JLong.h"@interfaceTestSVO:NSObject// 更多OC對(duì)應(yīng)java類型可在git上面查到,不一一列舉了@property(strong,nonatomic) JLong *uid;@property(strong,nonatomic) JInteger *status;@end
#import"TestSVO.h"@implementationTestSVO+ (NSString*)serializingAlias
{//這里返回的java中的完整報(bào)名+類名辱士,否則會(huì)出問題return@"com.test.web.socket.modules.user.svo.TestSVO";
}@end
假設(shè)我們要將上面的對(duì)象通過socket發(fā)送給服務(wù)器
Kryo *k = [Kryo new];// 創(chuàng)建一個(gè)內(nèi)存輸出流 用于輸出Kryo序列化后的東西NSOutputStream*outputStream = [[NSOutputStreamalloc] initToMemory];// KryoOutput這個(gè)類實(shí)際上就是NSOutputStream的子類KryoOutput *output = [[KryoOutput alloc] initWithStream:outputStream];
[k writeObject:message to:output];// toData獲取到NSDataNSData*contents = output.toData;intlen = (int)contents.length;// 發(fā)送數(shù)據(jù)NSData*lengthData = [NSDatadataWithBytes:&len length:sizeof(len)];
[self.socketwriteData:[selfdescBytesWithNSData:lengthData] withTimeout:WRITE_TIME_OUT tag:0];
[self.socketwriteData:contents withTimeout:WRITE_TIME_OUT tag:0];
[output close];
這樣子,Kryo的基本使用就告一段落了听绳。
轉(zhuǎn)載自:http://www.zhiyingme.com/a/xinwenzixun/mingjiaguandian/60.html