您的位置:首页 > 数据库 > Redis

redis客户端Jedis源码分析系列——集合JedisByteHashMap

2015-11-02 00:00 856 查看
摘要: 本文对redis客户端中实现的JedisByteHashMap进行源码分析

一、JedisByteHashMap

JedisByteHashMap是Jedis中实现存储键和值均为byte[]字节数组的Map集合类,它利用HashMap作为键-值对实际存储集合,对Map中的方法进行重写来达到Jedis需要的存储键-值对均为字节数组的需要。该类是非线程安全的。

二、源码分析

该类实现上没什么复杂的地方,个人觉得比较有趣的一个实现是对键进行了包装。HashMap在实现键值对映射时,会调用键的equals和hashCode方法,byte[]数组这两个方法均是从Object继承而来,显然不满足需求,于是JedisByteHashMap中的内部类对byte[]数组进行了简单的包装来满足需求,这实际上用到了适配器的设计思想。

private static final class ByteArrayWrapper {
private final byte[] data;

public ByteArrayWrapper(byte[] data) {
if (data == null) {
throw new NullPointerException();
}
this.data = data;
}

public boolean equals(Object other) {
if (!(other instanceof ByteArrayWrapper)) {
return false;
}
return Arrays.equals(data, ((ByteArrayWrapper) other).data);
}

public int hashCode() {
return Arrays.hashCode(data);
}
}


同样为了实现entrySet方法,返回键和值均为字节数组的Entry对象,JedisByteHashMap也实现了对Entry进行包装的内部类

private static final class JedisByteEntry implements Entry<byte[], byte[]> {
private byte[] value;
private byte[] key;

public JedisByteEntry(byte[] key, byte[] value) {
this.key = key;
this.value = value;
}

public byte[] getKey() {
return this.key;
}

public byte[] getValue() {
return this.value;
}

public byte[] setValue(byte[] value) {
this.value = value;
return value;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Jedis JedisByteHashMap