Preliminary use of the Redis learning record in Java

Source: Internet
Author: User
Tags benchmark key string set set redis server

1. About Redis
Redis:<span style= "font-family:arial, Helvetica, Sans-serif;" >http://download.csdn.net/detail/he90227/8569855</span>

What is Redis? Two sentences can be summarized as follows: 1. is a fully open source free Key-value memory Database 2. is generally considered a data structure server, mainly because of its rich data structure strings, map, list, sets, sorted sets it to adapt to different scenarios of storage requirements by providing a variety of key-value data types, and with many high-level interfaces to make it competent as the cache , the queue system and other roles are similar to memcached, but it solves the situation where the data is completely lost after a power outage, and she supports more of the untyped value types, in addition to string, supports lists (linked list), sets (collection), and Zsets (ordered collection) data types. These data types support Push/pop, Add/remove, and intersection-set and difference sets, and richer operations, all of which are atomic 2. Supported data type string types type string hash type Ha SH linked list Type lists collection type sets ordered collection type zsets Description: String is the simplest type you can understand with memcached The type of one mode, one key corresponds to a value, and the operation supported on it is similar to the operation of Memcached.     But it's more versatile. List is a linked list structure, the main function is push, pop, get all the values of a range and so on.     Key in operation is understood as the name of the linked list. Set is a set, and we are similar to the concept of the set in mathematics, the operation of the set has added delete elements, there are multiple sets of orthogonal and poor operation.     In Operation Key is understood as the name of the collection. Zset is an upgraded version of set, and he adds a sequential attribute on the set, which can be specified when adding a modified element, and Zset automatically re-adjusts the order of the new values after each assignment. It can be understood that there are two columns of MySQL table, one column of value, and one in the order of storage.     Key in operation is understood as the name of Zset. The hash data type allows users to store object types with Redis, an important advantage of the hash data type is that the memory consumption of the data store is small when you store only a few key values for the data object.   3. All of the data stored in the persistent redis database is stored in memory and provides support for persistence, namely, the ability to asynchronously write in-memory data to the hard disk without affecting continued service delivery     Redis master-slave configuration Redis supports Master-slave's master-slave configuration by specifying the SLAVEOF parameter as the host's IP and port in the slave configuration file 4. Redis VS Memcached 1. Can be used as a cache system for 2. Performance on Redis is a single-threaded model, Memcached supports multi-threading, and all of the latter on multi-core servers have higher performance some 3.Redis supports advanced data types and persistence features 4. Storage  Mode: memcached only supports simple key-value storage, does not support enumeration, does not support persistence and replication, etc. 5. Installing Redis--Redis officially supports only Linux, UNIX, and OS X and does not support Windowslinux installation: wget or copy to the specified directory---Unzip and use the Macke command in the SRC directory to complete the compilation wget Http://download.redis.io/redis-stable.tar.gztar XZF REDIS-STABLE.TAR.GZCD Redis-stablemake need to explain, Redis installation is very simple, already have a ready-made makefile file, run the make command directly. Makemake Installredis consists of four executable files: Redis-benchmark, Redis-cli, Redis-server, redis-stat four files, Adding a redis.conf constitutes the final available package for the entire redis. They function as follows: The daemon launcher for the Redis-server:redis server Redis-cli:redis the command-line operations tool. Of course, you can also use Telnet to operate the Redis-benchmark:redis Performance test tool based on its plain text protocol, test the read and write performance of Redis in your system and your configuration Redis-stat:redis status Detection Tool,                    Ability to detect Redis current status parameters and latency 6. Starting and stopping Redis compiled executable files redis-server----Redis server redis-cli ----Redis command-line client redis-server is a Redis server, and starting Redis is running REDIS-SERVERREDIS-CLI redis comes with redis command-line client, the important tool for learning Redis starts Redis 1. Direct boot-run redis-server to start Redis Note: Redis service Server uses 6379 ports by default, you can customize the port number used by the--port parameter Eg:redis-server--port 6380 stop Redis REDIS-CLI shut Down Redis may be synchronizing the in-memory data to the hard disk, forcing termination of the Redis process can result in data loss, and it is a good practice to send the shutdown command to Redis when Redis receives the shutdown command, all client connections are disconnected first. Then the persistence is performed according to the configuration, and finally the exit is completed


2.Redis Configuration and Common commands
1.Redis Configuration
redis.conf config file: Reference # whether to run as a daemon daemonize yes# configuration PID storage path and file name, the default is the current path pidfile Redis.pid#redis defaults listening ports Port 6379# client idle how many seconds after , disconnect timeout 300# log display level loglevel verbose# Specify the file name of the log output, or you can specify the number of the database to be set to the standard output port logfile stdout#, the default connected database is 0 and can be selected via the Select N to connect different databases databases 16# save data to disk policy # when there is a keys data is changed, 900 seconds to disk save 900 # When 10 keys data is changed, 300 seconds to disk save 300 10 #当有1w条keys数据被改变时, 60 seconds Refresh to disk once save 60 10000# when dump . RDB database is compressed data object Rdbcompression yes# Dump database data saved file name Dbfilename Dump.rdb#redis working directory dir/home/falcon/redis-2.0.0/###########  Replication ######### ############ #Redis的复制配置 # slaveof <masterip> <masterport># Masterauth <master-password>########### # # SECURITY ############ requirepass foobared############### LIMITS ############## #最大客户端连接数 # maxclients 128# maximum Memory Utilization # MaxMemory <bytes>########## APPEND only MODE ######### #是否开启日志功能appendonly no# rules for refreshing logs to disk # Appendfsync Alwaysappendfsync everysec# appendfsync no################ VIRTUAL MEMORY ########### #是否开启VM功能vm-enabled no# Vm-enaBled yesvm-swap-file logs/redis.swapvm-max-memory 0vm-page-size 32vm-pages 134217728vm-max-threads 4############# Advanced CONFIG ############## #glueoutputbuf yeshash-max-zipmap-entries 64hash-max-zipmap-value 512# Whether to reset the hash table activerehashing Yes

General operation Command 01exits key//test Specifies whether the key exists, return 1 indicates presence, 0 does not exist 02del key1 key2 .... KeyN//Delete the given key, return the number of deleted keys, 0 indicates that the given key does not exist 03type Key//Returns the value type of the given key. The return none indicates that there is no key,string character type, the list linked list type set unordered collection type ... 04keys pattern//Returns all keys that match the specified pattern, given below an example of 05randomkey//Returns a key randomly selected from the current database, if the current database is empty, returns an empty string of 06rename old Key Newkey//Atom rename a key, if Newkey exists, will be overwritten, return 1 indicates success, 0 failed. May be oldkey not present or Newkey same as 07renamenx oldkey Newkey//Ibid, but if Newkey exists return failed 08dbsize//Return key number of the current database 09expire key Seconds//Specifies the expiration time, in seconds, for the key. Returns 1 success, 0 indicates that key has set an expiration time or there is no 10ttl key//Returns the remaining expiration seconds of a key that has set an expiration time-1 means that key does not exist or has not set an expiration time of 11select Db-index// Select the database by index, the default connection database is all 0, the default number of databases is 16. Return 1 indicates success, 0 failure 12move key db-index//move key from current database to specified database. Returns 1 success. 0 This method does not fail if key does not exist or if it has already been 13flushdb//deleted in the specified database for all keys in the current database. With caution 14flushall//delete all keys in all databases, this method does not fail. More cautious with the string type Data Operation command 01set key value//set key corresponding to the value of string type of value, return 1 indicates success, 0 failed 02setnx key value//Ibid, if Key has alreadyexists, returns 0. NX is the meaning of not exist 03get key//Gets the string value corresponding to key, if key does not exist return Nil04getset key value//atomic set key, and returns the old value of key. If key does not exist return Nil05mget key1 Key2 ... keyN//Get more than one key at a time, if the corresponding key does not exist, the corresponding return nil. Here is an experiment, first emptying the current database, and then setting k1,k2. Get K3 corresponding return Nil06mset key1 value1 ... keyN valuen//Set the value of multiple keys at once, successfully returning 1 means that all values are set, Failure to return 0 means that no value is set for 07msetnx key1 value1 ... keyN valuen//Ibid, but does not overwrite the existing KEY08INCR key//to the value of key to do Gaga operation and return the new value. Note INCR A value that is not int will return an error, incr a nonexistent key, then set key to 109DECR key//Ibid, but do a decrement operation, decr a key is not present, then set key to -110incrby key I Nteger//With INCR, plus the specified value, key does not exist when the key is set, and that the original value is 011decrby key integer//with DECR, minus the specified value. Decrby is purely for readability, we can achieve the same effect by Incrby a negative value, and vice versa. 12append key value//appends value to the string value of the specified key, returning the length of the new string value. Here is an example of 13SUBSTR key start end//returns the string value of the truncated key, and note that the value of key is not modified. Subscript is starting from 0, and then the above example list type Data operation command 01lpush key string//in key corresponding to the head of the list to add a string element, return 1 indicates success, 0 means that key exists and is not a list type 02rpush key Strin G//Ibid, add 03llen key at tail//return key for the length of list, key does not existBack to 0, if the key corresponding type is not a list return error 04lrange key start end//return element within the specified interval, subscript starting from 0, negative value is calculated from the back, 1 means the penultimate element, key does not exist return empty list 05ltrim key start End//intercept list, keep elements within specified interval, successfully return 1,key no return error 06lset key index value//Set element value specified in list, successful return 1,key or subscript does not exist return error 07lrem key Count value//deletes the same element as count and value from the key corresponding list. Count is 0 time to delete all 08lpop keys//delete elements from the head of list and return deleted elements. If the key corresponds to the list does not exist or is empty returns nil, if the key corresponding value is not list returned error 09rpop//Ibid, but deleted from the tail 10blpop Key1...keyn Timeout//left-to-right scan returned to the A non-empty list is lpop and returned, such as Blpop List1 list2 list3 0, if the list does not exist LIST2,LIST3 is non-null LIST2 and returns the element removed from the Lpop. If all the lists are empty or nonexistent, the timeout second is blocked, and a timeout of 0 means that it is blocked. When blocking, if a client has a push operation on any key in Key1...keyn, the first client that is blocked on that key will return immediately. If the timeout occurs, nil is returned. A bit like a UNIX select or Poll11brpop//with Blpop, one is to remove from the head a 12rpoplpush srckey Destkey//from the tail to remove the trailing element from the Srckey corresponding list The element is added to the destkey corresponding to the head of the list, and finally the value of the removed elements is returned, and the entire operation is atomic. If Srckey is empty or does not exist return nilset type Data operation command 01sadd key member//Add a String element Returns 1 if the element and the set returned in the collection are not stored in the set set that corresponds to the 0,key.Return error 02srem Key member//removes the given element from key corresponding set, successfully returns 1 if member does not exist in the collection or key does not exist return 0 if key does not correspond to a value of set type return error 03spop key Delete and return the key corresponding to the set of a random element, if the set is empty or key does not exist return Nil04srandmember key//Same as Spop, randomly take an element in the set, but Do not delete the element 05smove Srckey Dstkey member//remove member from the Srckey corresponding set and add it to the dstkey corresponding set, the entire operation is atomic. Successful return 1 if member in Srckey does not exist return 0 if key is not set type return error 06scard key//Return set number of elements if set is empty or key does not exist return 007sismember K EY member//Determine if the member is in set, there is a return 1,0 that does not exist or the key does not exist 08sinter Key1 Key2...keyn//Returns the intersection of all given keys 09sinterstore DST  Key Key1...keyn//same as sinter, but will simultaneously save the intersection to Dstkey 10sunion key1 Key2...keyn//Returns the set of all the given key 11sunionstore Dstkey Key1...keyn Same as Sunion, and simultaneously save and set to Dstkey under 12sdiff key1 Key2...keyn//Returns the difference set of all given key 13sdiffstore Dstkey Key1...keyn//Same sdiff, and simultaneously saves the difference set To Dstkey under 14smembers key//return key corresponding to all elements of set, result is unordered sorted set type data Operation command 01zadd key score member//add Element To the collection, the element exists in the collection to update the corresponding Score02zrem key member//delete the specifiedElement, 1 indicates success, if the element does not exist return 003zincrby key INCR member//increase the score value of the corresponding member, then move the element and keep the skip list in order. Returns the updated score value of 04zrank key member//returns the rank (subscript) of the specified element in the collection, the elements in the collection are 05zrevrank key member//IBID., sorted by score from small to large, but the collection The elements in the element are sorted by score from large to small 06zrange key start end//similar to Lrange operation to specify interval elements from the collection. Returned is ordered result 07zrevrange key start end//Ibid, return result is press score reverse of 08zrangebyscore key min Max//return set score element in given interval 09zcount key Min Max//Returns the number of score in the set at a given interval 10zcard key//Returns the number of elements in the set 11zscore key element//returns the corresponding Score12zremrangebyrank key min Max//delete element ranking in a given interval 13zremrangebyscore key min Max//delete score element in given interval hash type data Operation command 01h Set key field value//sets the hash field to the specified value, and if key does not exist, first create a 02hget key field//Get the specified hash field03hmget key filed1 ..... fieldn//Get all specified hash filed04hmset key filed1 value1 ... filedn valuen//Set hash multiple Field05hincrby key field integer/ /Add the specified hash filed to the given Value 06hexists key field//test Specifies whether field exists 07hdel key field//delete specified hasH Field08hlen key//Returns field number of the specified hash 09hkeys key//return hash of all field10hvals key Return hash of all value11hgetall//return hash of all filed and value


3.redis uses 1.maven dependencies in Java:
<!--Redis dependent--><dependency>    <groupId>redis.clients</groupId>    <artifactId> jedis</artifactid>    <version>2.7.0</version></dependency><!--Spring integrates Redis dependencies- ><dependency>    <groupId>org.springframework.data</groupId>    <artifactId> Spring-data-redis</artifactid>    <version>1.5.0.RELEASE</version></dependency>

2. Client instances
Properties file Basic Configuration redis.pool.maxactive=100redis.pool.maxidle=20redis.pool.maxwait=3000redis.ip= localhostredis.port=6379


Import Java.util.resourcebundle;import Com.alibaba.fastjson.json;import Redis.clients.jedis.jedis;import Redis.clients.jedis.jedispool;import Redis.clients.jedis.jedispoolconfig;import Redis.clients.jedis.ShardedJedis Import Redis.clients.jedis.shardedjedispool;public class Redisclient {public static jedispool Jedispool;//pooling Management Jedis chain    Connection pool Static {//Read related configuration ResourceBundle resourcebundle = Resourcebundle.getbundle ("Redis");    int maxactive = Integer.parseint (resourcebundle.getstring ("redis.pool.maxActive"));    int maxidle = Integer.parseint (resourcebundle.getstring ("Redis.pool.maxIdle"));        int maxwait = Integer.parseint (resourcebundle.getstring ("redis.pool.maxWait"));    String IP = resourcebundle.getstring ("Redis.ip");        int port = integer.parseint (resourcebundle.getstring ("Redis.port"));      Jedispoolconfig config = new Jedispoolconfig ();    Set maximum number of connections config.setmaxtotal (maxactive);    Set maximum idle number config.setmaxidle (Maxidle); Set the timeout time Config.setmaxwaItmillis (maxwait);   Initialize Connection pool Jedispool = new Jedispool (config, IP, port); /** * Set string contents to cache * @param key key * @param value value * @return * @throws Exception */public static B    Oolean Set (String key,string value) throws exception{Jedis Jedis = null;      try {Jedis = Jedispool.getresource ();      Jedis.set (key, value);    return true;      } catch (Exception e) {e.printstacktrace ();    return false;    }finally{Jedispool.returnresource (Jedis); }}/** * Set object to cache * @param key * @param value * @return */public static Boolean set (String Key,object V    Alue) {Jedis Jedis = null;      try {String Objectjson = json.tojsonstring (value);      Jedis = Jedispool.getresource ();      Jedis.set (key, Objectjson);    return true;      } catch (Exception e) {e.printstacktrace ();    return false;    }finally{Jedispool.returnresource (Jedis); }}/** * Delete the cached object, depending on key * @param key * @return */PubliC Static Boolean del (String key) {Jedis Jedis = null;      try {Jedis = Jedispool.getresource ();      Jedis.del (key);    return true;      } catch (Exception e) {e.printstacktrace ();    return false;    }finally{Jedispool.returnresource (Jedis);    }}/** * Get content based on key * @param key * @return */public static Object get (String key) {Jedis Jedis = null;      try {Jedis = Jedispool.getresource ();      Object value = Jedis.get (key);    return value;      } catch (Exception e) {e.printstacktrace ();    return false;    }finally{Jedispool.returnresource (Jedis); }}/** * Gets the object based on key * @param key * @return */public static <T> T get (String key,class<t> clazz)    {Jedis Jedis = null;      try {Jedis = Jedispool.getresource ();      String value = Jedis.get (key);    return Json.parseobject (value, clazz);      } catch (Exception e) {e.printstacktrace ();    return null; }finally{Jedispool.returnresOurce (Jedis);  }}//private Jedis Jedis; Non-slicing Client connection//private Jedispool Jedispool; Non-slicing connection pool//private Shardedjedis Shardedjedis; Slicing database connection//private Shardedjedispool Shardedjedispool; Slice connection Pool////public redisclient () {//initialpool ();//initialshardedpool ();//shardedjedis = Shardedjedispool.getresource ();//jedis = Jedispool.getresource ();//}/////*//* Initialize non-tile pool//*///private void InitialPool () {////Pool basic configuration//jedispoolconfig config = new Jedispoolconfig ();//config.setmaxidle (5);//config.set//}////private void Initialshardedpool () {//shardedjedispool////}}

Test code Package Com.jay.demo6.redis.test;import Org.junit.test;public class Redisdemotest {/* * Add data that needs to be cached to Redis */@ testpublic void Setusercache () {//Add Save object to buffer Userdo user1 = new Userdo (); User1.setid (1111); User1.setsex (true); User1.setphone ("1783797435"); User1.setemail ("[email protected]");//Call method handles Boolean Resultcache = Redisclient.set (" User1 ", user1); if (Resultcache) {System.out.println (" Saves the object to the cache successfully. ");} else {System.out.println ("Failed to save object to cache. ");}} /* * Get Cached data from Reids */@Testpublic void Getusercahce () {Userdo user1 = redisclient.get ("user1", Userdo.class); if (user1!= NULL) {System.out.println (user1.tostring ());}}}
</pre><pre code_snippet_id= "637583" snippet_file_name= "blog_20150407_12_3514709" name= "code" class= "HTML" >package Com.jay.demo6.redis.test;public class Userdo {    private int id;    Private Boolean sex;& nbsp   private string name;    private string phone;    private string email;    public User Do () {        super ();   }    public int getId () {        RET Urn id;   }    public void setId (int id) {        this.id = id;   }&NB Sp   Public boolean issex () {        return sex;   }    public void Setsex (bool EAN sex) {        this.sex = sex;   }    public String getName () {    & nbsp   return name;   }    public void SetName (String name) {        this.name = name;  &nbsP  }    Public String getphone () {        return phone;   }    public void Setphone (String phone) {        This.phone = phone;   }    public String Getemai L () {        return email;   }    public void Setemail (String email) {  &nbs P     This.email = email;   }    @Override     public String toString () {  &nbs P     Return "Userdo [id=" + ID + ", sex=" + (sex? ") Male ":" female ") +", name= "+ name                +", phone= "+ Phone +", email= "+ Emai L + "]";   }}




Preliminary use of the Redis learning record 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.