Java操作Redis

1. 下載Jar

         jedis-2.5.1.jar

 

2. Java代碼

@Test

public void testDemo() {

    Jedis redis = new Jedis("192.168.89.30", 10123);

    // hset key field value將哈希表key中的域field的值設爲value

    redis.hset("bdliu""name""bdliu");

    redis.hset("bdliu""mail""[email protected]");

    redis.hset("bdliu""age""27");

    // 返回哈希表key中,一個或多個給定域的值。

    List<String> list = redis.hmget("bdliu""name""mail""age");

    for (String s : list) {

       System.out.println(s);

    }

    System.out.println("------------------");

    Map<String, String> res = redis.hgetAll("bdliu");

    Set set = res.keySet();

    for (Iterator it = set.iterator(); it.hasNext();) {

       String key = (String) it.next();

       String value = res.get(key);

       System.out.println(key + "::" + value);

    }

    System.out.println("------------------");

    System.out.println(redis.hget("bdliu""name"));

}

 

 

@Test

public void testMap() {

    // 同時將多個field - value(-)對設置到哈希表key

    Map<String, String> map = new HashMap<String, String>();

    map.put("uid""bdliu");

    map.put("pwd""bdliu");

    map.put("addr""湖南");

 

    Jedis redis = new Jedis("192.168.89.30", 10123);

    redis.hmset("map", map);

    System.out.println(redis.hget("map""addr"));

    System.out.println("------------------");

    //HGETALL key返回哈希表key中,所有的域和值。

    Map<String, String> res = redis.hgetAll("map");

    Set set = res.keySet();

    for (Iterator it = set.iterator(); it.hasNext();) {

       String key = (String) it.next();

       String value = res.get(key);

       System.out.println(key + "::" + value);

    }

}


@Test

public void testKeyValue() {

    Jedis redis = new Jedis("192.168.89.30"10123);

 

    System.out.println("------------------");

    String compy_name = redis.get("compy_name");

    if (compy_name != null) {

       System.out.println(compy_name);

       redis.set("compy_name""sina.com");

    }

    System.out.println("------------------");

}






 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章