Redis的hash資料類型及其應用情境解析---購物車

來源:互聯網
上載者:User
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);}}}


輸出結果












聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.