Akka-- ByteString

Immutable消息

Actor之间是通过消息沟通的,但为了避免同步问题,消息必须是Immutable。因此,Akka无法使用byte[]ByteBuffer,而是设计了ByteString来表示二进制数据。理解这一点很重要,因为ByteString是不可变的,所以ByteString的很多看似修改状态的方法实际上都是返回一个新的ByteString实例。如果对StringBigInteger等Java自带的不可变类比较了解,那么就很容易理解这一点。

Rope数据结构

ByteString是一种类似Rope的数据结构,如下图所示:

虽然在内部ByteString使用树形结构存储了n个小byte[],但从外部来看,ByteString仍然像是一个大的byte[]。

工厂方法

ByteString是抽象类,不能直接实例化。可以使用工厂方法来创建ByteString实例,ByteString提供了6个工厂方法,如下所示:

 

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. public static ByteString empty()  
  2. public static ByteString fromArray(byte[] array)  
  3. public static ByteString fromArray(byte[] array, int offset, int length)  
  4. public static ByteString fromString(String string)  
  5. public static ByteString fromString(String string, String charset)  
  6. public static ByteString fromByteBuffer(ByteBuffer buffer)  

empty()方法返回一个空的ByteString,其余方法可以根据byte[],String或者ByteBuffer来创建ByteString实例。需要注意的是,为了保证状态不可改变,工厂方法可能会对数据进行拷贝

 

常用方法

下面是比较常用的一些ByteString方法(我用String的类似方法给出解释):

  • public int size() // string.length()
  • public ByteString concat(ByteString bs) // string.concat(str)
  • public byte head() // string.charAt(0)
  • public ByteString tail() // string.substring(1, string.length())
  • public ByteString take(int n) // string.substring(0, n)
  • public ByteString drop(int n) // string.substring(n, string.length())
  • public ByteString slice(int from, int until) // string.substring(from, until)

ByteStringBuilder

大家都知道,在生成一个长字符串的时候,应该用StringBuilder类(或其线程安全版本StringBuffer)。出于同样的目的,Akka提供了ByteStringBuilder来创建ByteString。下面是ByteStringBuilder的用法示例:

 

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. ByteStringBuilder bsb = new ByteStringBuilder();  
  2. bsb.append(ByteString.fromString("abc"));  
  3. bsb.putByte((byte1);  
  4. bsb.putInt(32, ByteOrder.BIG_ENDIAN);  
  5. bsb.putDouble(3.14, ByteOrder.BIG_ENDIAN);  
  6. bsb.putBytes(new byte[] {123});  
  7. ByteString bs = bsb.result();  

 

ByteIterator

为了方便的访问ByteString里的数据,Akka提供了ByteIterator类。可以通过ByteString的iterator()方法获得一份ByteIterator实例,下面是ByteIterator的用法示例:

 

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. ByteIterator it = bs.iterator();  
  2. it.getByte();  
  3. it.getInt(ByteOrder.BIG_ENDIAN);  
  4. it.getDouble(ByteOrder.BIG_ENDIAN);  
  5. it.getBytes(new byte[10]);  

 

与java.io互操作

调用ByteStringBuilder的asOutputStream()方法,可以把ByteStringBuilder当成OutputStream来使用。调用ByteIterator的asInputStream()方法,可以把ByteIterator当做InputStream来使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值