Akka边学边写(3)-- ByteString介绍
Akka的IO层设计能够參考这篇文档,本文简介一下ByteString的设计。
Immutable消息
Actor之间是通过消息沟通的。但为了避免同步问题,消息必须是Immutable。
因此。Akka无法使用byte[]或ByteBuffer。而是设计了ByteString来表示二进制数据。理解这一点非常重要,由于ByteString是不可变的。所以ByteString的非常多看似改动状态的方法实际上都是返回一个新的ByteString实例。
假设对String或BigInteger等Java自带的不可变类比較了解。那么就非常easy理解这一点。
Rope数据结构
ByteString是一种类似Rope的数据结构,例如以下图所看到的:
尽管在内部ByteString使用树形结构存储了n个小byte[],但从外部来看。ByteString仍然像是一个大的byte[]。
工厂方法
ByteString是抽象类。不能直接实例化。能够使用工厂方法来创建ByteString实例,ByteString提供了6个工厂方法,例如以下所看到的:
public static ByteString empty()
public static ByteString fromArray(byte[] array)
public static ByteString fromArray(byte[] array, int offset, int length)
public static ByteString fromString(String string)
public static ByteString fromString(String string, String charset)
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的使用方法演示样例:
ByteStringBuilder bsb = new ByteStringBuilder();
bsb.append(ByteString.fromString("abc"));
bsb.putByte((byte) 1);
bsb.putInt(32, ByteOrder.BIG_ENDIAN);
bsb.putDouble(3.14, ByteOrder.BIG_ENDIAN);
bsb.putBytes(new byte[] {1, 2, 3});
ByteString bs = bsb.result();
ByteIterator
为了方便的訪问ByteString里的数据,Akka提供了ByteIterator类。
能够通过ByteString的iterator()方法获得一份ByteIterator实例,以下是ByteIterator的使用方法演示样例:
ByteIterator it = bs.iterator();
it.getByte();
it.getInt(ByteOrder.BIG_ENDIAN);
it.getDouble(ByteOrder.BIG_ENDIAN);
it.getBytes(new byte[10]);
与java.io互操作
调用ByteStringBuilder的asOutputStream()方法。能够把ByteStringBuilder当成OutputStream来使用。调用ByteIterator的asInputStream()方法。能够把ByteIterator当做InputStream来使用。
结论
ByteString从Immutable的角度来讲,和String非常相似(我猜这也是为什么起名为ByteString的原因)。
使用ByteString的时候,应该牢记这点。
最新文章
- django ftp 研究
- SQL获取汉字首字母
- A Guide to Creating a Quality Project Schedule
- RecyleView
- 深入理解 react-router 路由系统
- malloc_stats---检查内存泄露的神器
- CFUpdate高速模式下出现Error #2038提示的解决方案
- DynamoDB
- 图片预览(适用于IE6,9,10,Firefox)
- debian 9 安装 teamviewer 13
- 九度OJ1036-空缺数字计算-暴力破解
- C#微信小程序服务端获取用户解密信息
- How develop BigData Project in Visual Studio
- 运行spark官方的graphx 示例 ComprehensiveExample.scala报错解决
- js中定义属性和变量
- CentOS7.5最小化安装之后的配置
- 【题解】彩色树 51nod 1868 虚树 树上dp
- C# 基础连接已经关闭: 发送时发生错误
- ASP.NET 页面基本优化.
- PAT (Top Level)1002. Business DP/背包