java操作redis簡單樣本

來源:互聯網
上載者:User
java操作redis簡單樣本

    初學redis,在java語言和環境下完成redis的入門學習。              首先,官網下載源碼,編譯,安裝,修改設定檔redis.conf中的三項:     1. 注釋掉 bind 127.0.0.1     2. daemonize no 改為 daemonize yes     3. protected-mode yes 改為protected-mode no       這樣的話運行 redis-server  redis.conf 預設就是在後台啟動並執行了,而且,允許遠程主機串連。
    使用jedis作為驅動來完成java程式訪問redis伺服器,測試代碼如下:
    
Jedis jedis = new Jedis("192.168.100.103", 6379);res = jedis.ping();System.out.println(res);

     輸出PONG說明串連成功。

    1. 使用redis的list資料結構完成生產者-消費者模型
//Redis Server IP Portprivate static String redisServerIP = "192.168.100.103";private static int    redisServerPort= 6379;//生產者資料存放區隊列private static String key_src  = "task-queue";private static String key_tmp  = "tmp-queue";public static class Producer implements Runnable{Jedis jedis = new Jedis(redisServerIP, redisServerPort);public void run() {while(true) {//使用UUID類比產生了一個任務String str = UUID.randomUUID().toString();//排入佇列jedis.lpush(key_src, str);System.out.println("插入了一個新任務: " + str + "當前任務總數:" + jedis.llen(key_src));try {Random random = new Random();Thread.sleep(random.nextInt(500) + 500);} catch (InterruptedException e) {e.printStackTrace();}}}}public static class Consumer implements Runnable {Jedis jedis = new Jedis(redisServerIP, redisServerPort);public void run() {while(true) {//從隊列中取出任務String taskID = jedis.rpoplpush(key_src, key_tmp );if (taskID != null) {//處理任務//.....System.out.println("處理一個新任務: " + taskID + "當前任務總數: " + jedis.llen(key_src));}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}public static void main(String[] args) {new Thread(new Producer()).start();   //生產者線程new Thread(new Consumer()).start();  //消費者線程try {Thread.sleep(Long.MAX_VALUE);} catch (InterruptedException e) {e.printStackTrace();}}


     2. 採用hash結構完成最簡單的購物車模型
private static String redisServerIP = "192.168.100.103";private static int    redisServerPort= 6379;private static String hash_name  = "ShoppingCart";public static void main(String[] args) {Jedis jedis = new Jedis(redisServerIP, redisServerPort);//類比購物車中的資料Map<String, String> goodsMap = new HashMap<String, String>();goodsMap.put("java",    "5");goodsMap.put("C/C++",   "3");goodsMap.put("Node.js", "10");goodsMap.put("C#",      "10");//hmset命令jedis.hmset(hash_name, goodsMap);System.out.println("當前共有 " + jedis.hlen(hash_name) + "個fields");List<String> fields = new ArrayList<String>();Set<String> keySet = jedis.hkeys(hash_name);Iterator i = keySet.iterator();while (i.hasNext()) {fields.add(i.next().toString());}//hmget命令List<String> list = jedis.hmget(hash_name, fields.get(0), fields.get(1), fields.get(2));System.out.println(list);//hgetall命令Map<String, String> map = jedis.hgetAll(hash_name);Set<Entry<String, String>> entrySet = map.entrySet();for (Entry<String, String> entry: entrySet) {System.out.println(entry.getKey() + ": " + entry.getValue());}    jedis.disconnect();}

    3. 事物測試
private static String redisServerIP = "192.168.100.103";private static int    redisServerPort= 6379;public static void main(String[] args) {Jedis jedis = new Jedis(redisServerIP, redisServerPort);long start = System.currentTimeMillis();//開啟事物Transaction transaction = jedis.multi();Map<String, String> map = new HashMap<String, String>();    map.put("username", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");    map.put("password", "123456");    map.put("age",      "25");    map.put("gender",   "man");    map.put("email",    "XXXX@xxx.com");    map.put("address",  "中國廣東省深圳市");    map.put("tel",      "18888888888");    map.put("position", "軟體工程師");    map.put("birth_date",   "2016-01-01 00:00:00");    map.put("tel",       "2016-01-01 00:00:00");        int totalRecords = 1024;    for (int i = 0; i < totalRecords; i++) {    String key = "user_" + i;        Response<String> result = transaction.hmset(key, map);    }        //提交事物    List<Object> list = transaction.exec();    System.out.println("插入資料量: " + list.size());    long end = System.currentTimeMillis();    System.out.println("總共用時: " + ((end - start)/1000.0) + " seconds");    jedis.disconnect();}

    4. 採用zset完成最熱商品排序功能
private static String redisServerIP = "192.168.100.103";private static int    redisServerPort= 6379;private static String productTopNKey = "productTopN";//商品熱搜榜public static class ProductHotN implements Runnable {Jedis jedis = new Jedis(redisServerIP, redisServerPort);//構造熱搜的商品String[] productTopN = {"iPhone7 Plus", "P9 Plus", "XiaoMi Note", "Vivo X7 Plus", "Galaxy Note7"};//類比商搜尋次數的變化public void run() {while (true) {Random random = new Random();//隨機挑一個商品String product = productTopN[random.nextInt(5)];//搜尋度自增1jedis.zincrby(productTopNKey, 1, product);try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}}}//查看商品熱搜榜public static class HotViewer implements Runnable {Jedis jedis = new Jedis(redisServerIP, redisServerPort);int i = 1;public void run() {while (true) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("第" + i + "次擷取熱門排行榜");Set<Tuple> set = jedis.zrevrangeWithScores(productTopNKey, 0, -1);for (Tuple tuple: set) {System.out.println(tuple.getElement() + ": " + tuple.getScore());}i ++;}}}public static void main(String[] args) {new Thread(new ProductHotN()).start();new Thread(new HotViewer()).start();try {Thread.sleep(Long.MAX_VALUE);} catch (InterruptedException e) {e.printStackTrace();}}



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.