JavaではJedisを使用してRedisを操作します。


一.   redisのインストール
1.ソースをダウンロードし、解凍後ソースをコンパイルします。

[root@cwt123 ~]# tar xzf redis-2.8.3.tar.gz
[root@cwt123 ~]# cd redis-2.8.3
[root@cwt123 ~]# make
2.Redisサービスを開始します。(srcはredis-2.83で) 

[root@cwt123 ~]# cd src
[root@cwt123 ~] ./redis-server 
3.レディスクライアントを接続する

 [root@cwt123 ~]# ./redis-cli
4.テスト、redisのipはマシンのipで、ポートはデフォルトで6379です。

 127.0.0.1:6379> set 'hello' 'test'

OK

127.0.0.1:6379> get hello

"test"
二.   java操作redis
1.直接redisに接続し、redisを操作する

package com.sinovatech.mactivity.web.controller;

 

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

 

import org.junit.Before;

import org.junit.Test;

 

import redis.clients.jedis.Jedis;

 

public class TestredisOwn {

  private Jedis jedis; 

   

  @Before

  public void setup() {

    //  redis   ,192.168.0.100:6379

    jedis = new Jedis("10.143.131.63", 6378);

    //    

    //jedis.auth("admin"); 

  }

   

  /**

   * redis     

   */

  @Test

  public void testString() {

    //-----    ---------- 

    jedis.set("name","xinxin");// key-->name    value-->xinxin 

    System.out.println(jedis.get("name"));//    :xinxin 

     

    jedis.append("name", " is my lover"); //  

    System.out.println(jedis.get("name")); 

     

    jedis.del("name"); //     

    System.out.println(jedis.get("name"));

    //       

    jedis.mset("name","liuling","age","23","qq","476777XXX");

    jedis.incr("age"); //   1  

    System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));

     

  }

   

  /**

   * redis  Map

   */

  @Test

  public void testMap() {

    //-----    ---------- 

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

    map.put("name", "xinxin");

    map.put("age", "22");

    map.put("qq", "123456");

    jedis.hmset("user",map);

    //  user  name,    :[minxr]-->          List 

    //        redis map   key,       map     key,   key     ,      

    List<String> rsmap = jedis.hmget("user", "name", "age", "qq");

    System.out.println(rsmap); 

  

    //  map       

    jedis.hdel("user","age");

    System.out.println(jedis.hmget("user", "age")); //     ,      null 

    System.out.println(jedis.hlen("user")); //  key user          2 

    System.out.println(jedis.exists("user"));//    key user      true 

    System.out.println(jedis.hkeys("user"));//  map      key 

    System.out.println(jedis.hvals("user"));//  map      value 

  

    Iterator<String> iter=jedis.hkeys("user").iterator(); 

    while (iter.hasNext()){ 

      String key = iter.next(); 

      System.out.println(key+":"+jedis.hmget("user",key)); 

    } 

  }

   

  /** 

   * jedis  List 

   */ 

  @Test 

  public void testList(){ 

    //lpush           ,     key,        key      

    jedis.lpush("java framework","spring"); 

    jedis.lpush("java framework","struts"); 

    jedis.lpush("java framework","hibernate"); 

    //rpush             ,     key,        key      

    jedis.rpush("java frameworkr", "spring");

    jedis.rpush("java frameworkr", "struts");

    jedis.rpush("java frameworkr", "hibernate");

    //lpop,         ,    null

    jedis.lpop("java framework");

    //rpop         ,key     null

    jedis.rpop("java framework");

    //       jedis.lrange      , 

    //     key,        ,        ,jedis.llen     -1       

    System.out.println(jedis.lrange("java framework",0,-1)); 

     

  } 

   

  /** 

   * jedis  Set 

   */ 

  @Test 

  public void testSet(){ 

    //   

    jedis.sadd("user","liuling"); 

    jedis.sadd("user","xinxin"); 

    jedis.sadd("user","ling"); 

    jedis.sadd("user","zhangxinxin");

    jedis.sadd("user","who"); 

    //  noname 

    jedis.srem("user","who"); 

    System.out.println(jedis.smembers("user"));//       value 

    System.out.println(jedis.sismember("user", "who"));//   who    user      

    System.out.println(jedis.srandmember("user")); 

    System.out.println(jedis.scard("user"));//          

  } 

  

  @Test 

  public void test() throws InterruptedException { 

    //jedis    

    //  ,   rpush lpush List   。       (       ) 

    jedis.del("a");//     ,          

    jedis.rpush("a", "1"); 

    jedis.lpush("a","6"); 

    jedis.lpush("a","3"); 

    jedis.lpush("a","9"); 

    System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1] 

    System.out.println(jedis.sort("a")); //[1, 3, 6, 9] //        

    System.out.println(jedis.lrange("a",0,-1)); 

  } 

  //      redis     

  @Test

  public void testRedisPool() {

    TestRedisUtil.getJedis().set("newname", "    ");

    System.out.println(TestRedisUtil.getJedis().get("newname"));

  }

  public static void main(){

    Jedis jedis=TestRedisUtil.getJedis();

    jedis.set("testrediskey001", "testrediskey001");

    String getvalue=jedis.get("testrediskey001");

    System.out.println(getvalue);

  }

} 

2.Redis接続池を作成し、操作はredisを使用します。
①Redis接続池の作成

package com.sinovatech.mactivity.web.controller; 

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;

 

public final class TestRedisUtil {

   

  //Redis   IP

  private static String ADDR = "10.143.131.63";

   

  //Redis    

  private static int PORT = 6378;

   

  //    

  private static String AUTH = "admin";

   

  //           ,    8;

  //     -1,      ;  pool     maxActive jedis  ,   pool    exhausted(  )。

  private static int MAX_ACTIVE = 1024;

   

  //    pool         idle(   ) jedis  ,     8。

  private static int MAX_IDLE = 200;

   

  //           ,    ,    -1,      。        ,     JedisConnectionException;

  private static int MAX_WAIT = 10000;

   

  private static int TIMEOUT = 10000;

   

  // borrow  jedis   ,      validate  ;   true,    jedis       ;

  private static boolean TEST_ON_BORROW = true;

   

  private static JedisPool jedisPool = null;

   

  /**

   *    Redis   

   */

  static {

    try {

      JedisPoolConfig config = new JedisPoolConfig();

      config.setMaxIdle(MAX_ACTIVE);

      config.setMaxIdle(MAX_IDLE);

      config.setMaxWaitMillis(MAX_WAIT);

      config.setTestOnBorrow(TEST_ON_BORROW);

      jedisPool = new JedisPool(config, ADDR, PORT);

    } catch (Exception e) {

      e.printStackTrace();

    }

  }

   

  /**

   *   Jedis  

   * @return

   */

  public synchronized static Jedis getJedis() {

    try {

      if (jedisPool != null) {

        Jedis resource = jedisPool.getResource();

        return resource;

      } else {

        return null;

      }

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

   

  /**

   *   jedis  

   * @param jedis

   */

  public static void returnResource(final Jedis jedis) {

    if (jedis != null) {

      jedisPool.returnResource(jedis);

    }

  }

} 

②作成したRedis接続池を使ってRedisを操作する

package com.sinovatech.mactivity.web.controller; 

import redis.clients.jedis.Jedis; 

public class TestRedisOwnNew { 

  public static void main(String[] args) {

    // TODO Auto-generated method stub

  Jedis jedis=TestRedisUtil.getJedis();

    jedis.set("testrediskey001", "testrediskey001");

    String getvalue=jedis.get("testrediskey001");

    System.out.println(getvalue);

    jedis.del("testrediskey001");

     

  }

 

} 

三.Redisの常用方法
1.redis格納文字列:

//① -----    ----------   set  

    jedis.set("name","xinxin");// key-->name    value-->xinxin 

    System.out.println(jedis.get("name"));//    :xinxin 

    jedis.append("name", " is my lover"); //  

    System.out.println(jedis.get("name"));

//②    ,  del  

    jedis.del("name"); //     

    System.out.println(jedis.get("name"));

//③       ,  mset       (key,value,key,value)

    jedis.mset("name","liuling","age","23","qq","476777XXX");

//④incr  ,   key value    1  ,     key     ,  1

    jedis.incr("age"); //   1  

    System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
2.redis操作Map

//①-----    ----------   hmset  ,    map

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

    map.put("name", "xinxin");

    map.put("age", "22");

    map.put("qq", "123456");

    jedis.hmset("user",map);

    //  user  name,    :[minxr]-->          List 

    //        redis map   key,       map     key,   key     ,      

//②   ,  hmget  ,        map key,      list

    List<String> rsmap = jedis.hmget("user", "name", "age", "qq");

    System.out.println(rsmap); 

 

 //③   map       ,  hdel  ,       

    jedis.hdel("user","age");

    System.out.println(jedis.hmget("user", "age")); //     ,      null 

    System.out.println(jedis.hlen("user")); //  key user          2

    System.out.println(jedis.exists("user"));//    key user      true 

    System.out.println(jedis.hkeys("user"));//  map      key 

    System.out.println(jedis.hvals("user"));//  map      value

 

    Iterator<String> iter=jedis.hkeys("user").iterator(); 

    while (iter.hasNext()){ 

      String key = iter.next(); 

      System.out.println(key+":"+jedis.hmget("user",key)); 

    } 

3.jedis操作List

//①lpush           ,     key,        key      

    jedis.lpush("java framework","spring"); 

    jedis.lpush("java framework","struts"); 

    jedis.lpush("java framework","hibernate");

//②rpush             ,     key,        key      

    jedis.rpush("java frameworkr", "spring");

    jedis.rpush("java frameworkr", "struts");

    jedis.rpush("java frameworkr", "hibernate");

//③lpop,         ,    null

    jedis.lpop("java framework");

//④ rpop         ,key     null

    jedis.rpop("java framework");

//⑤        jedis.lrange      ,     key,        ,        ,jedis.llen     -1      

    System.out.println(jedis.lrange("java framework",0,-1)); 

以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。