Java Connection Redis Redis additions and deletions

Source: Internet
Author: User
Tags set set redis server

One, create a new MAVEN project, the project can be in the form of a jar or war, and then import the correct dependency

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>com.test</groupId> <artifactid>redis</ artifactid> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceencodin            g>utf-8</project.build.sourceencoding> </properties> <dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> &L t;version>2.5.0</version> </dependency> <dependency> <groupid>junit&lt            ;/groupid> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build><plugins><plugin><groupid>org.apache.maven.plugins</gro upid><artifactid>maven-compiler-plugin</artifactid><version>2.0.2</version>< configuration><source>1.8</source><target>1.8</target></configuration></ Plugin></plugins></build> </project>

Ii. Building a tool class to connect to the Redis database

 PackageCom.xiangjun.redis;ImportRedis.clients.jedis.Jedis;ImportRedis.clients.jedis.JedisPool;ImportRedis.clients.jedis.JedisPoolConfig; Public classRedisutil {
Server IP AddressPrivate StaticString ADDR = "23.228.103.10";
PortPrivate Static intPORT = 6379; PasswordPrivate StaticString AUTH = "123456"; Maximum number of connections to a connection instancePrivate Static intMax_active = 1024;
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。 Private Static intMax_idle = 200;
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException Private Static intMax_wait = 10000;
time when the connection timed outPrivate Static intTIMEOUT = 10000;
  // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的; Private Static BooleanTest_on_borrow =true; Private StaticJedispool Jedispool =NULL; /*** Initializing Redis connection pool*/ Static { Try{jedispoolconfig config=NewJedispoolconfig (); Config.setmaxtotal (max_active); Config.setmaxidle (Max_idle); Config.setmaxwaitmillis (max_wait); Config.settestonborrow (Test_on_borrow); Jedispool=Newjedispool (config, ADDR, PORT, TIMEOUT, AUTH); } Catch(Exception e) {e.printstacktrace (); } } /*** Get Jedis instances*/ Public synchronized StaticJedis Getjedis () {Try { if(Jedispool! =NULL) {Jedis resource=Jedispool.getresource (); returnresource; } Else { return NULL; } } Catch(Exception e) {e.printstacktrace (); return NULL; } } /*** * * release Resources*/ Public Static voidReturnresource (FinalJedis Jedis) { if(Jedis! =NULL) {Jedispool.returnresource (Jedis); } } }

Third, the Redis additions and deletions of the test

 PackageCom.xiangjun.redis;ImportJava.util.HashMap;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.Map;ImportRedis.clients.jedis.Jedis; Public classTestredis {PrivateJedis Jedis; /*** Connect to Redis server*/     Public voidConnectredis () {Jedis=Redisutil.getjedis (); }        /*** Redis Operation string*/     Public voidteststring () {//Add DataJedis.set ("name", "Youcong"); System.out.println (Jedis.get ("Name")); //Stitching StringsJedis.append ("Name", ". com"); System.out.println (Jedis.get ("Name")); //Delete DataJedis.del ("name"); System.out.println (Jedis.get ("Name")); //set multiple key-value pairsJedis.mset ("name", "YC", "Age", "all", "QQ", "1933108196"); JEDIS.INCR ("Age");//plus 1 OperationSystem.out.println (Jedis.get ("name") + "-" + jedis.get ("age") + "-" +jedis.get ("QQ")); }            /*** Redis Operations Map Collection*/     Public voidTestMap () {//Add Datamap<string,string> map =NewHashmap<string,string>(); Map.put ("Name", "YC"); Map.put ("Age", "22"); Map.put ("QQ", "1933108196"); Jedis.hmset ("User", map); //remove the name from the users and execute the result:[minxr]--> note that the result is a generic list//The first parameter is the key that is stored in the map object in Redis followed by the key that is placed in the Map object, and the following key can be multiple, variablelist<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"));//If there is a record of key 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)); }        }        /*** Redis Operations List Collection*/     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 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)); }            /*** Redis Operation Set Set **/         Public voidTestset () {//AddJedis.sadd ("User", "liuling"); Jedis.sadd ("User", "Xinxin"); Jedis.sadd ("User", "Ling"); Jedis.sadd ("User", "zhangxinxin"); Jedis.sadd ("User", "who"); //DeleteJedis.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                                    }            /*** Redis Sort*/         Public voidTestsort () {//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)); System.out.println (Jedis.sort ("a"));//[1,3,6,9]//enter results after sortingSystem.out.println (Jedis.lrange ("A", 0,-1)); }            /*** Redis Connection Pool*/         Public voidTestredispool () {Redisutil.getjedis (). Set ("NewName", "Test"); System.out.println (Redisutil.getjedis (). Get ("NewName")); }         Public Static voidMain (string[] args) {Testredis test=NewTestredis ();        Test.connectredis ();    Test.testsort (); }}

Java Connection Redis Redis additions and deletions

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.