Redis's Java additions and deletions

Source: Internet
Author: User
Tags set set

Tag:sina    Support    type   hostname   www    bbb   end    hash     function    

Jedis is a Redis client implementation of Java. To use Jedis, you need to join Jedis's maven dependency:<dependency> <groupId>redis.clients</groupId> <artifactId> Jedis</artifactid> <version>2.4.2</version></dependency>redis simplest use: Jedis Jedis = new Jedis ("localhost");//Use Redis default port 6379jedis.set ("foo", "Bar"); String value = Jedis.get ("foo"), but the Jedis object is not thread-safe. In a multithreaded environment will be silly, so the official provides a thread-safe connection pool: jedispool pool = new Jedispool (new Jedispoolconfig (), "localhost"), can be directly set to static global variables. Because spring is always used. Configuration one: <bean id= "Jedispoolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "Maxtotal" Val Ue= "${redis.maxtotal}"/> <property name= "Maxidle" value= "${redis.maxidle}"/> <property name= "max Waitmillis "value=" ${redis.maxwaitmillis} "/> <property name=" Testonborrow "value=" true "/> <prope Rty name= "Testonreturn" value= "true"/> </bean><bean id= "Jedispool" class= "Redis.clients.jedis.JedisPool "> <constructor-arg Index= "0" ref= "jedispoolconfig"/> <constructor-arg index= "1" value= "${redis.hostname}"/> <constr Uctor-arg index= "2" value= "${redis.port}"/> </bean>ok.  can start to work: Jedis Jedis = Jedispool.getresource (); try {////... do stuff here ... for example jedis.set ("foo", "Bar");  String foobar = jedis.get ("foo"); Jedis.zadd ("Sose", 0, "car");   Jedis.zadd ("Sose", 0, "bike"); Set<string> sose = Jedis.zrange ("Sose", 0,-1);} catch (Jedisconnectionexception e) {//Returnbrokenresource when the state of the object is unrecoverable if (null        ! = Jedis) {pool.returnbrokenresource (Jedis);    Jedis = null; }} finally {///... it ' s important to return the Jedis instance to the pool once you ' ve finished using it if (null! = J Edis) Pool.returnresource (Jedis);} ... when closing your Application:pool.destroy ();//If not destroy. The connection in the connection pool will always be attached. Until the timeout expires. So writing a destroy method in the spring container is still necessary for Redis transaction support (transactions). I would like to do a few things at the same time, during which I can not do anything else, I will put these fewThings in the same thing. Transaction t = Jedis.multi (); T.set ("AAA", "111"); T.set ("BBB", "222"); T.exec (); Distributed client (Shardedjedis) I personally understand that this thing is a load balancer, using the XXX hashing algorithm, the key is stored evenly on different redisserver jedispoolconfig with the above, The second parameter is the list of redisserver <bean id= "Shardedjedispool" class= "Redis.clients.jedis.ShardedJedisPool" > <                Constructor-arg index= "0" ref= "jedispoolconfig"/> <constructor-arg index= "1" > <list> <bean class= "Redis.clients.jedis.JedisShardInfo" > <constructor-arg index= "0" value= "${redis.hostname}"/> <constructor-arg index= "1" value= "${redis.port}"/> </b ean> </list> </constructor-arg> </bean> use: Shardedjedis Jedis = Pool.getresource (  Jedis.set ("A", "foo"), ...//Do your work herepool.returnresource (Jedis); ...//a few moments Latershardedjedis Jedis2 = Pool.getresource (); Jedis.set ("Z", "bar");p Ool.returnresource (Jedis);p Ool.destroy (); Because the transaction is in the server-End implementations. In a distributed scenario, each batch of calling objects can access different machines. So, it's impossible to do business.     Import java.util.ArrayList;     Import Java.util.HashMap;     Import Java.util.Iterator;     Import java.util.List;     Import Java.util.Map;     Import Java.util.Set;     Import Redis.clients.jedis.Jedis; public class Jedisdemo {public void test1 () {Jedis Redis = new Jedis ("192.168.10.64", 6379);//Connection Redi S Redis.auth ("Redis");//Verify Password/*------------------------------------------------------------  -----------------------------------------------*//** key operation//keys Set KEYS              = Redis.keys ("*");//list all keys to find a specific key such as: Redis.keys ("foo") Iterator T1=keys.iterator ();                  while (T1.hasnext ()) {Object obj1=t1.next ();              System.out.println (OBJ1); //del removes the given one or more keys.              If the key does not exist, the command is ignored.              Redis.del ("name1");              TTL returns the remaining lifetime of a given key (time to live) (in seconds)Redis.ttl ("foo");              PERSIST key removes the time to live for a given key.              Redis.persist ("foo");                 EXISTS checks to see if a given key exists.              Redis.exists ("foo"); Move key DB moves the key of the current database (default 0) to the given database db.              If the current database (the source database) and the given database (the target database) have the same name as a given key, or if key does not exist in the current database, then move has no effect whatsoever. Redis.move ("foo", 1);//move Foo This key to database 1//rename key Newkey rename key to Newkey. Returns an error when key and Newkey are the same or key does not exist.

When Newkey already exists, the rename command overwrites the old value. Redis.rename ("foo", "Foonew"); Type key returns the types of values stored by key.

System.out.println (Redis.type ("foo"));//none (key does not exist), string (string), List (list), set (set), Zset (ordered set), hash (hash table)//expir E key seconds sets the time to live for a given key. When key expires, it is actively deleted by itself. Redis.expire ("foo", 5);//5 seconds expire//expireat expireat function as expire, which is used to set the time to live for the key.

The difference is that the time parameter accepted by the Expireat command is a UNIX timestamp (Unix timestamp). The simplest sort usage of the general sort usage is the sort key. Redis.lpush ("Sort", "1"); Redis.lpush ("Sort", "4"); Redis.lpush ("Sort", "6"); Redis.lpush ("Sort", "3"); Redis.lpush ("Sort", "0"); List List = Redis.sort ("sort");//default is ascending for (int i=0;i<list.size (); i++) {System.out.println (List.get (i)); } */ /* ---------------------------------------------------------------------------------------------- -------------*//** string Operation//set key value Associates a string value of values to a key. Redis.set ("name", "Wangjun1"); Redis.set ("id", "123456"); Redis.set ("Address", "Guangzhou"); Setex Key seconds values associates the value to the key and sets the lifetime of the key to seconds (in seconds). Redis.setex ("foo", 5, "haha"); MSET key value [key value ...] Set one or more key-value pairs at the same time. Redis.mset ("haha", "111", "XiXi "," 222 "); Redis.flushall (); Clears all key System.out.println (Redis.dbsize ()),//dbsize is the number of keys//append key value hypothesis Ke Y already exists and is a string. The append command appends value to the original value of the key. Redis.append ("foo", "00");//Assuming that key already exists and is a string, the append command appends value to the original value of the key.

GET key returns the string value associated with key Redis.get ("foo"); MGET key [key ...] returns the value of all (one or more) given key list List = Redis.mget ("haha", "Xixi"); for (int i=0;i<list.size (); i++) {System.out.println (List.get (i)); //DECR Key minus one of the numeric values stored in key. Decrby key Decrement the value stored by the key minus the decrement decrement.

INCR key adds a number value stored in key.

Incrby key increment adds an incremental increment to the value stored by key. */ /* --------------------------------------------------------------------------------------------------------- --*//** hash operation//hset key field value sets the values of the field field in hash key to value. Redis.hset ("website", "Google", "www.google.cn"); Redis.hset ("website", "Baidu", "www.baidu.com"); Redis.hset ("website", "Sina", "www.sina.com"); Hmset key field value [field value ...] sets multiple field-value (domain-value) pairs to the hash table key at the same time.

Map map = new HashMap (); Map.put ("Cardid", "123456"); Map.put ("username", "Jzkangta"); Redis.hmset ("hash", map); Hget key field returns the value of the given field field in the hash table key. System.out.println (Redis.hget ("hash", "username")); Hmget key field [field ...] Returns the value of one or more given fields in a hash table key.

List List = Redis.hmget ("website", "Google", "Baidu", "Sina"); for (int i=0;i<list.size (); i++) {System.out.println (List.get (i)); //hgetall key returns all fields and values in the hash table key.

map<string,string> map = Redis.hgetall ("hash"); For (Map.entry Entry:map.entrySet ()) {System.out.print (Entry.getkey () + ":" + entry.getvalue () + "\ T"); }//hdel key field [field ...] Deletes one or more specified domains in the hash table key. Hlen Key returns the number of fields in the hash table key. Hexists key field to view the hash table key, whether the given domain field exists.

Hincrby key field increment adds an incremental increment to the value of the field field in the hash table key. Hkeys key returns all fields in the hash table key.

Hvals key returns all the values in the hash table key.

*/ /* --------------------------------------------------------------------------------------------------------- --*//** LIST operation//lpush key value [value ...] Inserts the value values into the table header of the list key. Redis.lpush ("list", "abc"); Redis.lpush ("list", "Xzc"); Redis.lpush ("list", "Erf"); Redis.lpush ("list", "BNH"); Lrange Key start stop returns the element in the specified interval in the list key, with the interval specified by the offset start and stop.

The

Index parameter start and stop are all base 0, that is, 0 represents the first element of the list, 1 represents the second element of the list, and so on. You can also use a negative subscript to 1 for the last element of the list, 2 to represent the penultimate element of the list, and so on. List List = Redis.lrange ("list", 0,-1); for (int i=0;i<list.size (); i++) {System.out.println (List.get (i)); //llen Key returns the length of the list key. Lrem Key count value removes the element in the list that is equal to the value of the parameter, based on the count of the parameters. */ /* --------------------------------------------------------------------------------------------------------- --*//** SET Operation//sadd Key member [member ...] Add the member element to the collection key. Redis.sadd ("Testset", "S1"); Redis.sadd ("Testset", "S2"); Redis.sadd ("Testset", "S3"); Redis.sadd ("Testset", "S4"); Redis.sadd ("Testset", "S5"); Srem Key member removes the member element from the collection. Redis.srem ("Testset", "S5"); Smembers Key returns all members of the collection key.

Set set = Redis.smembers ("Testset"); Iterator T1=set.iterator (); while (T1.hasnext ()) {Object obj1=t1.next (); System.out.println (OBJ1); //sismember Key member infers whether the member element is a member of the collection key. Yes (true), otherwise (false) System.out.println (Redis.sismember ("Testset", "S4")); SCard Key returns the cardinality of the collection key (the number of elements in the collection).

Smove Source Destination member moves the member element from the source collection to the destination collection. SINTER key [Key ...] Returns all the members of a collection that are the intersection of all given collections.

Sinterstore destination key [key ...] This command is equivalent to sinter, but it saves the result to the destination collection instead of simply returning the result set//sunion key [key ...] Returns all members of a collection. The collection is the set of all the given sets. Sunionstore destination key [key ...] This command is equivalent to Sunion, but it saves the result to the destination collection instead of simply returning the result set. Sdiff key [Key ...] Returns all the members of a collection that are the set of differences for all given sets. Sdiffstore destination key [key ...] This command is equivalent to Sdiff. However, it saves the result to the destination collection instead of simply returning the result set. */}/** * @param args */public static void main (string[] args) {JEDISDE Mo T1 = new Jedisdemo (); T1.test1 (); }


?

Redis's Java 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.