Java operation Redis

Redis Java client Jedis

Jar packages required by Jedis: commons-pool-1.6.jar and jedis-2.1.0.jar

Source address: http://download.csdn.net/download/qq_36135928/10216836Click to open the link

Test connectivity:

public class TestPing {

         publicstatic void main(String[] args) {

                   //Connect to Redis service

                   Jedisjedis = new Jedis("192.168.237.131",6379);

                   //Check whether the service is running, and print PONG to indicate OK

                   System.out.println(jedis.ping());

         }

}

++++++

A key plus five data types

public class TestDataType {

         publicstatic void main(String[] args) {

                   Jedisjedis = new Jedis("192.168.237.131",6381);

             //key

             Set<String> keys =jedis.keys("*");

             for (Iterator iterator = keys.iterator();iterator.hasNext();) {

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

               System.out.println(key);

             }

             //String

            jedis.set("name","clare");

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

                   jedis.mset("str1","v1","str2","v2","str3","v3");

            System.out.println(jedis.mget("str1","str2","str3"));

             //list

            jedis.lpush("mylist","v1","v2","v3","v4","v5");

             List<String> list =jedis.lrange("mylist",0,-1);

             for (String element : list) {

               System.out.println(element);

             }

           //set

             jedis.sadd("orders","jd001");

             jedis.sadd("orders","jd002");

             jedis.sadd("orders","jd003");

              Set<String> set1 =jedis.smembers("orders");

              for (Iterator iterator = set1.iterator();iterator.hasNext();) {

                String string = (String) iterator.next();

                System.out.println(string);

              }

             jedis.srem("orders","jd002");

             System.out.println(jedis.smembers("orders").size());

              //hash

             jedis.hset("hash1","userName","lisi");

              System.out.println(jedis.hget("hash1","userName"));

              Map<String,String> map = newHashMap<String,String>();

             map.put("telphone","1111111111");

             map.put("address","iponkan");

             map.put("email","[email protected]");

              jedis.hmset("hash2",map);

              List<String> result =jedis.hmget("hash2", "telphone","email");

              for (String element : result) {

                System.out.println(element);

              }

              // zset

             jedis.zadd("zset01",60d,"v1");

             jedis.zadd("zset01",70d,"v2");

              jedis.zadd("zset01",80d,"v3");

             jedis.zadd("zset01",90d,"v4");

             

              Set<String> s1 =jedis.zrange("zset01",0,-1);

              for (Iterator iterator = s1.iterator();iterator.hasNext();) {

                String string = (String)iterator.next();

                System.out.println(string);

              }

         }

}

+++++++

Transaction commit:

daily

public class TestTransaction {

           public boolean transMethod() {

                     Jedis jedis = newJedis("192.168.237.131",6381);

                     int balance; // available balance

                     int debt; // debt

                     int amtToSubtract = 10;// Actual brush amount

                     jedis.watch("balance");

                    //jedis.set("balance","5");

                     balance =Integer.parseInt(jedis.get("balance"));

                     if (balance < amtToSubtract) {

                       jedis.unwatch();

                       System.out.println("modify");

                       return false;

              } else {

                System.out.println("***********transaction");

                Transaction transaction = jedis.multi();

                transaction.decrBy("balance",amtToSubtract);

                transaction.incrBy("debt",amtToSubtract);

                transaction.exec();

                balance =Integer.parseInt(jedis.get("balance"));

                debt =Integer.parseInt(jedis.get("debt"));

                System.out.println("*******" +balance);

                System.out.println("*******" +debt);

                return true;

              }

           }

           public static void main(String[] args) {

                     TestTransaction test = new TestTransaction();

               boolean retValue = test.transMethod();

               System.out.println("mainretValue-------: " + retValue);

           }

}

lock

public class TestWatch {

         publicstatic void main(String[] args) {

                   Jedisjedis = new Jedis("192.168.237.131",6381);

                    //Monitor the key, if the transaction should be moved, it will be abandoned

              jedis.watch("serialNum");

             jedis.set("serialNum","s#####################");

              jedis.unwatch();

              Transaction transaction = jedis.multi();//Executed as a command

              Response<String> response =transaction.get("serialNum");

             transaction.set("serialNum","s002");

              response =transaction.get("serialNum");

             transaction.lpush("list3","a");

             transaction.lpush("list3","b");

             transaction.lpush("list3","c");

              transaction.exec();

              //2 transaction.discard();

             System.out.println("serialNum***********"+response.get()); 

         }

}

  /**

   * In layman's terms, the watch command is to mark a key. If a key is marked, if the key is modified by others before committing the transaction, the transaction will fail. This situation can usually be done in the program.

   * Try again.

   * First mark the key balance, and then check whether the balance is sufficient. If the balance is insufficient, cancel the mark without deduction; if it is enough, start the transaction to perform the update operation.

   * If the key balance is modified by others during this period, it will report an error when submitting the transaction (executing exec). The program can usually catch such errors and re-execute it again until it succeeds.

   */

 

Master-slave replication:

 publicclass TestMasterSlave {

         publicstatic void main(String[] args) throws InterruptedException {

                   Jedisjedis_M = new Jedis("192.168.237.131",6381);

             Jedis jedis_S = newJedis("192.168.237.131",6379);

            jedis_S.slaveof("192.168.237.131",6381);

             jedis_M.set("k6","v6");

             Thread.sleep(500);

            System.out.println(jedis_S.get("k6"));

         }

}

JedisPool:

To obtain a Jedis instance, it needs to be obtained from the JedisPool; when the Jedis instance is used up, it needs to be returned to the JedisPool; if the Jedis makes an error during use, it also needs to be returned to the JedisPool.

Configuration summary all:

Most of the configuration parameters of JedisPool are assigned by the corresponding items of JedisPoolConfig.

public class JedisPoolUtil {

         privatestatic volatile JedisPool jedisPool = null;//The variable modified by volatile will not be cached by the local thread, and the read and write of the variable are all direct operations on the shared memory.

           private JedisPoolUtil() {}

           public static JedisPoolgetJedisPoolInstance()

          {

              if(null == jedisPool)

             {

                synchronized (JedisPoolUtil.class)

               {

                   if(null == jedisPool)

                  {

                    JedisPoolConfig poolConfig = newJedisPoolConfig();

                    poolConfig.setMaxActive(1000);

                    poolConfig.setMaxIdle(32);

                    poolConfig.setMaxWait(100*1000);

                    poolConfig.setTestOnBorrow(true);

                    

                    jedisPool = newJedisPool(poolConfig,"192.168.237.131",6381);

                  }

               }

             }

              return jedisPool;

          }

           public static void release(JedisPooljedisPool,Jedis jedis)

          {

              if(null != jedis)

             {

               jedisPool.returnResourceObject(jedis);

             }

          }

}

 

public class TestPollUtil {

         publicstatic void main(String[] args) {

                    JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance ();

              Jedis jedis = null;

              try

              {

                jedis = jedisPool.getResource();

               jedis.set("k8","v8");  

              } catch (Exception e) {

                e.printStackTrace ();

              }finally{

                JedisPoolUtil.release(jedisPool, jedis);

              }

         }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325595628&siteId=291194637