Add, delete, modify, and query Redis in java

Source: Internet
Author: User
Tags set set redis server

Add, delete, modify, and query Redis in java

Jedis is implemented on the java redis client. To use jedis, you need to add the maven dependency of jedis: <dependency> <groupId> redis. clients </groupId> <artifactId> jedis </artifactId> <version> 2.4.2 </version> </dependency> redis is the simplest application: jedis jedis = new Jedis ("localhost"); // use the default redis port 62.16jedis. set ("foo", "bar"); String value = jedis. get ("foo"); but the jedis object is not thread-safe, and it will be silly in a multi-threaded environment, so the official provision of a thread-safe connection pool: jedisPool pool = new JedisPool (new JedisPoolConfig (), "localhost"); you can directly Set it to a static global variable. Because spring is always used, configure one: <bean id = "jedisPoolConfig" class = "redis. clients. jedis. jedisPoolConfig "> <property name =" maxTotal "value =" $ {redis. maxTotal} "/> <property name =" maxIdle "value =" $ {redis. maxIdle} "/> <property name =" maxWaitMillis "value =" $ {redis. maxWaitMillis} "/> <property name =" testOnBorrow "value =" true "/> <property name =" testOnReturn "value =" true "/> </bean> <bean id = "jedisPool" class = "redis. clients. je Dis. jedisPool "> <constructor-arg index =" 0 "ref =" jedisPoolConfig "/> <constructor-arg index =" 1 "value =" $ {redis. hostname} "/> <constructor-arg index =" 2 "value =" $ {redis. port} "/> </bean> OK, you can start working: 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 <S Tring> 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 ve finished using it if (null! = Jedis) pool. returnResource (jedis );}///... when closing your application: pool. destroy (); // if no destroy exists, the connection in the connection pool will be connected until the timeout occurs, therefore, it is necessary to write a destroy method in the spring container to support redis transactions (transactions ). To put it bluntly, I want to do several things at the same time, but I can't do anything at the same time. I will put these things in the same thing. Transaction t = jedis. multi (); t. set ("AAAS", "111"); t. set ("bbb", "222"); t.exe c (); distributed client (ShardedJedis) I personally understand that this is a server Load balancer, using the xxx hash algorithm, store keys evenly on different redis servers. The second parameter is the redis Server LIST <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 "> <cons Tructor-arg index = "0" value = "$ {redis. hostname} "/> <constructor-arg index =" 1 "value =" $ {redis. port} "/> </bean> </list> </constructor-arg> </bean> usage: 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"); pool. returnResource (jedis); pool. destroy (); because the transaction is in the service In distributed mode, each batch of calling objects may access different machines. Therefore, transactions cannot be performed. 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); // connect to redis. auth ("redis"); // verify the password/* Verify /*-------------------------------------------------------------------------------------- --------------------- * // ** KEY operation // KEYS Set keys = redis. keys ("*"); // list all keys and find specific keys such as redis. keys ("foo") Iterator t1 = keys. iterator (); while (t1.hasNext () {Object obj1 = t1.next (); System. out. println (obj1);} // DEL removes one or more given keys. If the key does not exist, ignore this command. Redis. del ("name1"); // TTL returns the time to live (in seconds) of the given key for redis. ttl ("foo"); // PERSIST key removes the survival time of a given key. Redis. persist ("foo"); // EXISTS checks whether the given key EXISTS. Redis. exists ("foo"); // MOVE key db moves the key of the current database (0 by default) to the given database db. If the current database (source database) and the given database (target database) have a given key with the same name, or the key does not exist in the current database, moving has no effect. Redis. move ("foo", 1); // move the key foo to database 1 // RENAME key newkey to change the key to newkey. If the key and newkey are the same or do not exist, an error is returned. When newkey already exists, the RENAME Command overwrites the old value. Redis. rename ("foo", "foonew"); // TYPE key returns the TYPE of the value stored in the key. System. out. println (redis. type ("foo"); // none (key does not exist), string (string), list (list), set (set), zset (sorted set ), hash (hash table) // EXPIRE key seconds sets the survival time for the given key. When the key expires, it is automatically deleted. Redis. expire ("foo", 5); // expired in 5 seconds // EXPIREAT serves the same purpose as EXPIRE and is used to set the survival time for the key. The difference is that the time parameter accepted by the EXPIREAT command is UNIX timestamp ). // Generally, the simplest SORT method is 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"); // The default value is ascending for (int I = 0; I <list. size (); I ++) {System. out. println (list. get (I);} * // * Others * // ** STRING operation // SET key value associates the STRING value with the key. Redis. set ("name", "wangjun1"); redis. set ("id", "123456"); redis. set ("address", "guangzhou"); // SETEX key seconds value associates the value with the key and sets the key's survival time to seconds (in seconds ). Redis. setex ("foo", 5, "haha"); // MSET key value [key value...] simultaneously sets one or more key-value pairs. Redis. mset ("haha", "111", "xixi", "222"); // redis. flushAll (); clears all key systems. out. println (redis. dbSize (); // dbSize is the number of keys // APPEND key value if the key already exists and is a string, the APPEND Command appends the value to the original value of the key. Redis. append ("foo", "00"); // if the key already exists and is a string, the APPEND Command appends the value to the original value of the key. // GET key returns the string value associated with the key redis. get ("foo"); // MGET key [key...] returns the Value List of all (one or more) given keys = redis. mget ("haha", "xixi"); for (int I = 0; I <list. size (); I ++) {System. out. println (list. get (I);} // DECR key: Reduce the number value stored in the key by one. // DECRBY key decrement: subtract the value stored in the key from the decrement. // INCR key adds the number value stored in the key to one. // INCRBY key increment adds the value stored in the key with the incremental increment. * // * Partition * // ** Hash operation // HSET key field value sets the field value of the Hash table 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...] set multiple field-value pairs to the hash table key. Map map = new HashMap (); map. put ("cardid", "123456"); map. put ("username", "jzkangta"); redis. hmset ("hash", map); // HGET key field returns the field value of the given field in the hash table key. System. out. println (redis. hget ("hash", "username"); // hmet key field [field...] returns the values of one or more given fields in the hash table key. List list = redis. hmet ("website", "google", "baidu", "sina"); for (int I = 0; I <list. size (); I ++) {System. out. println (list. get (I);} // HGETALL key returns all the 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 fields in the hash table key. // HLEN key returns the number of fields in the hash table key. // Check whether the specified field exists in the hash table key in HEXISTS key field. // HINCRBY key field increment adds incremental increment to the field value in the hash table key. // HKEYS key returns all fields in the hash table key. // HVALS key returns all values in the hash table key. * // * Tables * // ** LIST Operation // LPUSH key value [value...] inserts the value into the header of the LIST key. Redis. lpush ("list", "abc"); redis. lpush ("list", "xzc"); redis. lpush ("list", "erf"); redis. lpush ("list", "bnh"); // The LRANGE key start stop operation returns the elements in the specified range of the list key. The range is specified by the offset start and stop. Both the start and stop parameters of the subscript (index) are based on 0, that is, 0 indicates the first element of the list, 1 indicates the second element of the List, and so on. You can also use negative subscript to represent the last element of the list in-1,-2 to represent the second-to-last 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);} // The length of the list key returned by LLEN key. // LREM key count value removes the elements in the list that are equal to the parameter value based on the value of the parameter count. * // * Member * // ** SET operation // SADD key member [member...] Add the member element to the SET key. Redis. sadd ("testSet", "s1"); redis. sadd ("testSet", "s2"); redis. sadd ("testSet", "s3"); redis. sadd ("testSet", "s4"); redis. sadd ("testSet", "s5"); // the SREM key member removes the member element from the set. Redis. srem ("testSet", "s5"); // SMEMBERS key returns all members in the set key. Set set = redis. smembers ("testSet"); Iterator t1 = set. iterator (); while (t1.hasNext () {Object obj1 = t1.next (); System. out. println (obj1);} // SISMEMBER key member determines whether the member element is a member of the set key. Yes (true); otherwise (false) System. out. println (redis. sismember ("testSet", "s4"); // SCARD key returns the base number of the set key (the number of elements in the set ). // SMOVE source destination member moves the member element from the source set to the destination set. // SINTER key [key...] returns all the members of a set, which is the intersection of all the given sets. // SINTERSTORE destination key [key...] this command is equivalent to SINTER, But it saves the result to the destination set, instead of simply returning the result set // SUNION key [key...] returns all members of a set, which is the union of all given sets. // SUNIONSTORE destination key [key...] This command is equivalent to SUNION, But it saves the result to the destination set instead of simply returning the result set. // SDIFF key [key...] returns all the members of a set, which is the difference set of all given sets. // SDIFFSTORE destination key [key...] This command is equivalent to SDIFF, But it saves the result to the destination set instead of simply returning the result set. * //}/*** @ Param args */public static void main (String [] args) {JedisDemo t1 = new JedisDemo (); t1.test1 ();}


 

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.