---
title: " Akka-- ByteString"
author: "wbj0110"
date: "2016-07-11T12:11:49Z"
tags: []
categories: ["编程语言"]
slug: "akka-bytestring"
draft: false
lastmod: "2016-07-11T12:11:49Z"
id: 2310450
url: "https://soledede.iteye.com/blog/2310450"
---

## Immutable消息

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

## []()Rope数据结构

ByteString是一种类似[Rope](http://en.wikipedia.org/wiki/Rope_%28data_structure%29)的数据结构，如下图所示：

![](http://upload.wikimedia.org/wikipedia/commons/8/8a/Vector_Rope_example.svg)

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

## []()工厂方法

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

 

**\[java]** [view plain](http://blog.csdn.net/zxhoo/article/details/40151377 "view plain") [copy](http://blog.csdn.net/zxhoo/article/details/40151377 "copy")

 

 [![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/486332 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/486332/fork "派生到我的代码片")

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](http://blog.csdn.net/zxhoo/article/details/40151377 "view plain") [copy](http://blog.csdn.net/zxhoo/article/details/40151377 "copy")

 

 [![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/486332 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/486332/fork "派生到我的代码片")

1. ByteStringBuilder bsb = new ByteStringBuilder();
2. bsb.append(ByteString.fromString("abc"));
3. bsb.putByte((byte) 1);
4. bsb.putInt(32, ByteOrder.BIG\_ENDIAN);
5. bsb.putDouble(3.14, ByteOrder.BIG\_ENDIAN);
6. bsb.putBytes(new byte\[] {1, 2, 3});
7. ByteString bs = bsb.result();

 

## []()ByteIterator

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

 

**\[java]** [view plain](http://blog.csdn.net/zxhoo/article/details/40151377 "view plain") [copy](http://blog.csdn.net/zxhoo/article/details/40151377 "copy")

 

 [![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/486332 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/486332/fork "派生到我的代码片")

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来使用。