Using Jedis to operate Redis in Java

Source: Internet
Author: User
Tags redis server

Using Java to operate Redis requires Jedis-2.1.0.jar,:http://files.cnblogs.com/liuling/jedis-2.1.0.jar.zip

If you need to use a Redis connection pool, you need to Commons-pool-1.5.4.jar,:http://files.cnblogs.com/liuling/commons-pool-1.5.4.jar.zip

 Packagecom.test;ImportJava.util.HashMap;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.Map;ImportOrg.junit.Before;Importorg.junit.Test;ImportRedis.clients.jedis.Jedis; Public classTestredis {PrivateJedis Jedis; @Before Public voidSetup () {//Connect to a Redis server, 192.168.0.100:6379Jedis =NewJedis ("192.168.0.100", 6379); //Authority authenticationJedis.auth ("admin"); }        /*** Redis Storage string*/@Test Public voidteststring () {//-----Add Data----------Jedis.set ("name", "Xinxin");//put the value-->xinxin into the Key-->nameSystem.out.println (Jedis.get ("name"));//execution Result: XinxinJedis.append ("Name", "Is My Lover");//StitchingSystem.out.println (Jedis.get ("name")); Jedis.del ("Name");//Delete a keySystem.out.println (Jedis.get ("name")); //set multiple key-value pairsJedis.mset ("name", "LiuLing", "Age", "all", "QQ", "476777XXX"); JEDIS.INCR ("Age");//to add 1 operationsSystem.out.println (Jedis.get ("name") + "-" + jedis.get ("age") + "-" + jedis.get ("QQ")); }        /*** Redis Operation Map*/@Test Public voidTestMap () {//-----Add Data----------map<string, string> map =NewHashmap<string, string>(); Map.put ("Name", "Xinxin"); Map.put ("Age", "22"); Map.put ("QQ", "123456"); Jedis.hmset ("User", map); //remove the name from the user and execute the result:[minxr]--> note that the result is a generic list//The first parameter is the key to the Map object in Redis, followed by the key of the object placed in the map, followed by the key can be more than a variable parameterlist<string> Rsmap = jedis.hmget ("User", "name", "Age", "QQ"));            System.out.println (RSMAP); //Delete a key value from a mapJedis.hdel ("User", "age"); System.out.println (Jedis.hmget ("User", "age");//because it was deleted, NULL is returned .System.out.println (Jedis.hlen ("user"));//returns the number of values stored in the key for user 2System.out.println (jedis.exists ("user"));//whether there is a record of key for user returns trueSystem.out.println (Jedis.hkeys ("user"));//returns all keys in the map objectSystem.out.println (jedis.hvals ("user"));//returns all the value in the Map objectIterator<String> Iter=jedis.hkeys ("User"). iterator ();  while(Iter.hasnext ()) {String key=Iter.next (); SYSTEM.OUT.PRINTLN (Key+ ":" +jedis.hmget ("user"), key)); }      }        /*** Jedis Operation list*/@Test Public voidtestlist () {//Remove all content before startingJedis.del ("Java framework"); System.out.println (Jedis.lrange ("Java framework", 0,-1)); //store three data in the key Java framework firstJedis.lpush ("Java framework", "Spring"); Jedis.lpush ("Java framework", "struts"); Jedis.lpush ("Java framework", "Hibernate"); //and then take out all the data jedis.lrange is out by range,//The first one is key, the second is the starting position, the third is the end position, Jedis.llen gets the length-1 means get allSystem.out.println (Jedis.lrange ("Java framework", 0,-1)); Jedis.del ("Java framework"); Jedis.rpush ("Java framework", "Spring"); Jedis.rpush ("Java framework", "struts"); Jedis.rpush ("Java framework", "Hibernate"); System.out.println (Jedis.lrange ("Java framework", 0,-1)); }          /*** Jedis Operation set*/@Test Public voidTestset () {//AddJedis.sadd ("User", "liuling"); Jedis.sadd ("User", "Xinxin"); Jedis.sadd ("User", "Ling"); Jedis.sadd ("User", "zhangxinxin"); Jedis.sadd ("User", "who"); //Remove NonameJedis.srem ("User", "who"); System.out.println (Jedis.smembers ("User"));//get all the added valueSystem.out.println (Jedis.sismember ("user", "who");//determine if who is an element of the user collectionSystem.out.println (Jedis.srandmember ("User")); System.out.println (Jedis.scard ("User"));//returns the number of elements in a collection} @Test Public voidTest ()throwsinterruptedexception {//Jedis Sort//Note that the Rpush and Lpush here are the operations of the list. is a doubly linked list (but from a performance perspective)Jedis.del ("a");//clear the data before adding data to testJedis.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]//enter results after sortingSystem.out.println (Jedis.lrange ("a", 0,-1)); } @Test Public voidTestredispool () {Redisutil.getjedis (). Set ("NewName", "Chinese test"); System.out.println (Redisutil.getjedis (). Get ("NewName")); }}

Redis Connection Pool:

 Packagecom.test;ImportRedis.clients.jedis.Jedis;ImportRedis.clients.jedis.JedisPool;ImportRedis.clients.jedis.JedisPoolConfig; Public Final classRedisutil {//Redis Server IP    Private StaticString ADDR = "192.168.0.100"; //the port number of the Redis    Private Static intPORT = 6379; //Access Password    Private StaticString AUTH = "admin"; //the maximum number of available connection instances, with a default value of 8;//If the assignment is-1, it is unrestricted, and if the pool is already assigned a maxactive Jedis instance, the state of the pool is exhausted (exhausted) at this time.     Private Static intMax_active = 1024; //controls the maximum number of Jedis instances in a pool that have an idle (idle) state, and the default value is 8.     Private Static intMax_idle = 200; //The maximum time to wait for an available connection, in milliseconds, and the default value is-1, which means that never times out. If the waiting time is exceeded, the jedisconnectionexception is thrown directly;    Private Static intMax_wait = 10000; Private Static intTIMEOUT = 10000; //whether validate operations are performed in advance when a Jedis instance is borrow, and if true, the resulting Jedis instances are available;    Private Static BooleanTest_on_borrow =true; Private StaticJedispool Jedispool =NULL; /*** Initializing Redis connection pool*/    Static {        Try{jedispoolconfig config=NewJedispoolconfig ();            Config.setmaxactive (max_active);            Config.setmaxidle (Max_idle);            Config.setmaxwait (max_wait);            Config.settestonborrow (Test_on_borrow); Jedispool=Newjedispool (config, ADDR, PORT, TIMEOUT, AUTH); } Catch(Exception e) {e.printstacktrace (); }    }        /*** Get Jedis instances *@return     */     Public synchronized StaticJedis Getjedis () {Try {            if(Jedispool! =NULL) {Jedis resource=Jedispool.getresource (); returnresource; } Else {                return NULL; }        } Catch(Exception e) {e.printstacktrace (); return NULL; }    }        /*** Release Jedis resources *@paramJedis*/     Public Static voidReturnresource (FinalJedis Jedis) {        if(Jedis! =NULL) {Jedispool.returnresource (Jedis); }    }}

Using Jedis to operate Redis in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.