【Java】实现类似与redis的hash存储操作(key ------ field --------value)

数据模型如下
time typeA valueA

time typeB valueB
此种数据存储模式跟redis的hash操作类似,key ------ field --------value式的存储结构,决定采用java进行抽象

key选择用String类型,field和value采用一个整体,类似于map进行处理,为了让map有序输入,采用LinkedHashMap,最终抽象出来的编码如下:

import java.util.LinkedHashMap;
import java.util.Map;
@SuppressWarnings({ "rawtypes", "serial" })
public class HashInfo extends LinkedHashMap{
	private Map sub = new LinkedHashMap();
	/**
	 * 设置sub.
	 *
	 * @param   sub  设置HashInfo类型变量   sub
	 */
	public void setSub(Map sub) {
		this.sub = sub;
	}
	@SuppressWarnings("unchecked")
	public synchronized void hset(String key,String hkey,Object value){
		sub = (Map) this.get(key);
		if(sub == null){
			sub = new LinkedHashMap();
		}
		sub.put(hkey, value);
		this.put(key, sub);
	}
	public synchronized Object hget(String key,String hkey){
		Map sub = (Map) this.get(key);
		if(sub != null){
			return sub.get(hkey);
		}
		return null;
	}
}

测试程序如下:

 
package util;

public class HashInfoTest {
 
	public static void main(String[] args) {
		HashInfo hash = new HashInfo();
		hash.hset("key", "field", "value");
		System.out.println(hash.hget("key", "field"));
	}
 
}

你可能感兴趣的:(redis,java,hashmap)