1.Hash資料結構
Redis中的Hashes類型可以看成具有String Key和String Value的map容器
2.Hash儲存購物車資料的操作
3.java代碼實現
import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import org.junit.After;import org.junit.Before;import org.junit.Test;import redis.clients.jedis.Jedis;/** * *//** * <p>Title: RedisHashTest</p> * <p>Description: </p> * <p>Company: </p> * @author 夏 傑 * @date 2015年12月14日 上午11:12:57 * @vesion 1.0*/public class RedisHashTest {Jedis jedis = null;@Beforepublic void before(){jedis = new Jedis("127.0.0.1",6379);}@Afterpublic void after(){jedis.disconnect();}/** * 插入一條資料 * */@Testpublic void hset(){// 插入一條hash資料(購物車)到redis庫中jedis.hset("cart:user00001", "深入理解JVM", "1");}/** * 插入多條資料 */@Testpublic void hmset(){//一次性往已經存在的這條hash資料(購物車)中添加多個field-value對HashMap<String, String> productMap= new HashMap<String, String>();productMap.put("SpringMVC從入門到精通", "2");productMap.put("進階JS攻城獅寶典", "2");//hmset添加多條資料jedis.hmset("cart:user00001", productMap);}/** * 只取出所有的key-value */@Testpublic void hgetAll(){//從購物車中擷取指定使用者的,所有的商品及其數量Map<String, String> catMap = jedis.hgetAll("cart:user00001");Set<Entry<String, String>> entrySet = catMap.entrySet();System.out.println("----------取出購物籃中的商品及數量資訊---------");for(Entry<String, String> entry:entrySet){System.out.println(entry.getKey() +":" +entry.getValue());}}/** * 只取出所有的keys */@Testpublic void hkeys(){System.out.println("----------只取出購物籃中的商品列表---------");// 從購物車中擷取所有的商品Set<String> products = jedis.hkeys("cart:user00001");for(String p:products){System.out.println(p);}}}
輸出結果