Redis Database Learning précis-writers

Source: Internet
Author: User

1.redis installation: Download the ZIP package, unzip, and then CMD terminal to enter the Redis installation root path

1.1 Starting the Redis server: Redis-server.exe "redis.windowws.conf"--"" in parentheses can be added without

1.2 (need to open another CMD terminal) Redis Client link on database: Redis-cli.exe-h database service IP address-P port "-a password"

Example: Redis-cli.exe-h 127.0.0.1-p 6379

Redis Service started successfully:


Redis Database Link succeeded:

================================= digression =================================

Redis configuration: Configuration: Config Set configuration name configuration value--view configuration: Config get configuration name

Example:

127.0.0.1:6379> config get loglevel
1) "LogLevel"
2) "notice"

Redis security: When a password is set, the client connects to the Redis service and requires a password authentication, otherwise the command cannot be executed.

Config set Requirepass "pass"

Config set Requirepass "pass"

Verify Password:

AUTH "Pass"

======================

Three conditions are available in the Redis default configuration file:

Save 900 1 (for 1 changes in 900s (15 minutes), Redis server is stored on disk drive)

Save (300s (5 minutes) with 10 changes,Redis server is stored on disk drive )

Save 10000 (10,000 changes within 60s,redis server is stored on disk drive )

redis is stored in memory, so it reads and writes very quickly. But the data is not secure. , the in-memory data is lost if the power outage occurs during execution.

Therefore, Redis configures the save instruction to store the disk drive within the specified time. Simultaneously create a dump.rdb file in the Redis root directory

each time the save instruction is executed, thedump.rdb file (under the Redis root directory on the local hard disk) is updated once.

1.save: Hard disk storage made by the server

2.bgsave: the command executes in the background client, making hard disk storage.

====> Recover data If you need to recover data, simply move the backup file (DUMP.RDB) to the Redis installation directory and start the service. To get the Redis directory, you can use the CONFIG command, as shown below

===========================================================================


2.Redis is completely open source free, comply with BSD protocol, is a high-performance Key-value database.

Redis supports five types of data: string (String), hash (hash), list, set (set), and Zset (sorted set: Ordered set).

The string type is the most basic data type of Redis, and a key can store up to 512MB.

Add <==> Read data:

String type: Add a: Set key Name Value--fetch: Get Key Name

Add multiple: Mset key1 value1 key2 value2 .....--Take: Mget key1 key2 ........ .....

127.0.0.1:6379> mset "S1" "1" "S2" "2" "  S3" "3"
OK
127.0.0.1:6379> mget s1 s2 S3
1) "1"
2) "2" 
  3) "3"

====> extension directive: INCR--plus 1 operation

Example: S1:0--INCR s1 after-->s1:1

127.0.0.1:6379> set S1 0
OK
127.0.0.1:6379> get s1
"0"
127.0.0.1:6379> incr s1
(integer ) 1
127.0.0.1:6379> get s1
"1"
127.0.0.1:6379>

Hash (hash) Type: Add one: Hset key value--fetch: Hget Key Name

Add multiple: Hmset Key Name (field field value) value

--Take one: Hget Key Name field value, take all: Hgetall Key Name

Delete a field value in a hash: Hdel Key Name Segment name

Add a specified value to a field in the hash: Hincrby Hash name fields specify values

--Example: Hincyby userinfo age 10 (Append +10 to original age)

Examples: The properties of the UserInfo class are: Name,age,sex

127.0.0.1:6379> hmset userinfo Name "Tom" Age-Sex "man"
OK
127.0.0.1:6379> hget userinfo name
"Tom" c3/>127.0.0.1:6379> hgetall userinfo
1) "Name"
2) "Tom"
3) "Age"
4) "[
5]" "Sex"
6) "Man"

To delete a field value in a hash:

127.0.0.1:6379> hgetall userinfo
1) "Name"
2) "Tom"
3) "Age"
4) "[
5]" "Sex"
6) "Man "
127.0.0.1:6379> hdel userinfo sex
(integer) 1
127.0.0.1:6379>
127.0.0.1:6379> Hgetall userinfo
1) "Name"
2) "Tom"
3) "Age"
4) "12"

List type: (When taken out, in reverse order when entering) increase the reverse:

Lpush Key Name value--take: Lrange Key name start index (0 start) subscript End Index

(when removed, according to the positive Order of entry) Increase:

Rpush Key Name value--take: Lrange Key name start index (0 start) subscript End Index

127.0.0.1:6379> Lpush list1 1
(integer) 1
127.0.0.1:6379> Lpush list1 2
(integer) 2
127.0.0.1:6379> Lpush list1 3
(integer) 3
127.0.0.1:6379> lrange list1 0 2
1) "3"
2) "2"
3) "1"
127.0.0.1:6379>
127.0.0.1:6379>
127.0.0.1:6379> rpush list2 a
(integer) 1
127.0.0.1:6379> Rpush list2 b
(integer) 2
127.0.0.1:6379> Rpush list2 C
(integer) 3
127.0.0.1:6379> lrange list2 0 2
1) "a"
2) "B"
3) "C"
127.0.0.1:6379>

Set (list) type: unordered

Add one: Sadd Key Name member name--fetch: Smembers Key Name

Add multiple: Sadd Key name Member1 name Member2 member3 name ...---Take: Smembers Key Name

(Note: sadd set1 aa bb cc AA BB, members have been added AA,BB automatically no longer added when the member has been duplicated ...) )

Example:

127.0.0.1:6379> sadd set1 aa bb cc dd AA bb
(integer) 4
127.0.0.1:6379>
127.0.0.1:6379>
127.0.0.1:6379> smembers set1
1) "AA"
2) "BB"
3) "CC"
4) "DD"
127.0.0.1:6379>

Note: AA,BB has been added two times in the above example, but the second inserted element is ignored based on the uniqueness of the elements within the collection.


Zset (sorted set: Ordered set) Redis Zset and set are also collections of string-type elements and do not allow duplicate members.

The difference is that each element is associated with a double-type fraction. Redis is a small-to-large ordering of the members in a collection by fractions.

Zset members are unique, but fractions (score) can be duplicated.

(such as a student's score of 75 points, the student can no longer have another score, the student's only.)

However, there are several students who have 75 points. So the score: 75 points can be repeated)

Zadd command:

Add one: Zadd Key name score member name--fetch: Smembers Key Name

Add multiple: Zadd Key Name (Score1 1 members) (Score2 2 members) (Score3 3 members) .......

--The 1th kind takes: Zrangebyscore stuscore 0 100 (this 0-100 refers to the score score,50 points, 60 points ....) )

--The 2nd kind takes: Zrange stuscore 0 2 "withscores--means results with score display" (This 0-2 refers to subscript index, starting from 0 ....) )

Note: And the zset is sorted when removed.

Added: STU1 60 points, STU2 50 points, STU3 90 points, order taken out: STU2 50 points, stu1 60 points, STU3 90 points

127.0.0.1:6379> zadd stuscore stu1
(integer) 1
127.0.0.1:6379> zadd stuscore stu2
(integer) 1
  127.0.0.1:6379> zadd stuscore stu3
(integer) 1
127.0.0.1:6379> zrangebyscore stuscore 0
1) " STU2 "
2)" STU1 "
3)" Stu3 "
127.0.0.1:6379> zrange stuscore 0 2
1)" STU2 "
2)" STU1 "
3)" Stu3 "
127.0.0.1:6379> zrange stuscore 0 2 withscores
1)" STU2 "
2)" [3] "
stu1"
4) "60" c18/>5) "Stu3"
6) "127.0.0.1:6379> zadd stuscore" Stu4 "Stu5" Stu6
(integer) 3

===========================================================================

Instruction Highlights:

Remove Key:del Key Name

Verify that there is a specified key:exists key name (return: 0--does not exist)

Get all current key names: Key *,

Gets the key name at the beginning of all current good: Key good*,

Take all field names/field values of key in hash: Hkeys Key name/hvals Key Name

127.0.0.1:6379> Hkeys User
1) "Name"
2) "Age"
127.0.0.1:6379> hvals user
1) "Tom"
2) "12"

INCR---plus 1 operation (increment 1)

DECR---minus 1 operations (decrement 1)

Append Key Name "character B"--stitching the character B after the value of the key name

Move Key Example: 1 "0......16"----to move key value pairs to 1 libraries, 2 libraries, 3 libraries ..... Inject (such as a key with the same name moved in) does not move

FLUSHDB-Clears all key-value pairs in the current library.



=====================================

Instruction learning in the 3.redis terminal see:

Http://www.runoob.com/redis/redis-keys.html

For more commands please refer to: https://redis.io/commands


4.redis Transaction Execution (command template: 1.multi open transaction 2 ...). A series of instruction operations 3.exec starts executing the transaction)

Here is an example of a transaction that begins a transaction with MULTI , then enqueue multiple commands into the transaction, and finally the EXEC command triggers the transaction, executing all the commands in the transaction:

(After receiving the EXEC command into the transaction execution, the execution of any command in the transaction fails, the remaining commands are still executed)

Redis 127.0.0.1:6379> MULTI
ok

redis 127.0.0.1:6379> SET book-name "Mastering C + + in + days"
queued< C5/>redis 127.0.0.1:6379> GET book-name
QUEUED

redis 127.0.0.1:6379> sadd Tag "C + +" "Programming" " Mastering Series "
QUEUED

redis 127.0.0.1:6379> smembers tag
QUEUED

Redis 127.0.0.1:6379>  EXEC
1) OK
2) "Mastering C + + in + days"
3) (integer) 3
4) 1) "Mastering Series"
   2) "C + +"
   3) "Programming"
Note: The execution of Redis transactions is not atomic. (either a successful or a failed operation is called an atomic operation.) )

In Redis transaction execution, the failure of an instruction does not result in the rollback of the previous instruction, nor does it cause subsequent instructions to fail.

5.Java using Redis:

Package controller;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Set;

Import Java.util.TreeSet;

Import Redis.clients.jedis.Jedis; public class Testconnetredis {public static void main (string[] args) {//Connect local Redis service//notation one: Jedis Jedis = new Jedi
		S ("localhost");
		Notation Two: Jedis Jedis = new Jedis ("127.0.0.1", 6379);
        If you set a password, you need to verify the password Jedis.auth ("pass");
        SYSTEM.OUT.PRINTLN ("Connection succeeded");
See if the service is running System.out.println ("service is running:" +jedis.ping ()); <======================= to this point, the Java link Redis database successfully ======================> System.out.println ("<============
        
        = To this point, the Java link Redis database successfully ============> ");
        
        /** * Starting to apply Redis database: *///java the String type (string) instance of Redis applied javauseredisbystring (Jedis);
        
        Java Application Redis hash type (hash) instance Javauseredisbyhash (Jedis); Java Application Redis's list (list) instance Javauseredisbylist (Jedis);
        
        Java applies a set type (set) instance of Redis Javauseredisbyset (Jedis);
        
	Java application Redis's all Keys instance Javauseredisgetkeys (Jedis); /** * Java application Redis String type (String) instance */public static void Javauseredisbystring (Jedis Jedis) {//Set number of Redis strings
		According to ===> CMD terminal directive: Set STR1 (Key name) "111" (Value name) jedis.set ("str1", "111");
		Jedis.set ("str2", "222");
	
		Jedis.set ("Str3", "333");
		Gets the stored data and outputs the instructions in the ===> corresponding CMD terminal: Get str1 (Key name) System.out.println ("redis-stored string str1:" + jedis.get ("str1"));
		System.out.println ("redis-stored string str2:" + jedis.get ("str2"));
		
	System.out.println ("redis-stored string STR3:" + jedis.get ("STR3")); }/** * Java application Redis hash type (hash) instance */private static void Javauseredisbyhash (Jedis Jedis) {//set redis hash data = =
		= = command in cmd terminal: Hset User (Key name) "Name" "Tom" (Value name) jedis.hset ("User", "name", "Tom");
		Jedis.hset ("User", "Age", "12");
	
		Jedis.hset ("User", "Sex", "boy"); Get the stored data and output the ===> corresponding to the cmd terminal in the instruction: Hgetall useR (key name) or: Hget User (key name) Name Field name System.out.println ("Redis stored hash data all derive hgetall:user as:" + jedis.hgetall ("user")); /* Print: The hash data for Redis storage is all derived hgetall:user: {sex=boy, age=12, name=tom}*/System.out.println ("Hash data for Redis storage: User's name:
		"+ jedis.hget (" user "," name "));
		SYSTEM.OUT.PRINTLN ("Redis stored hash data: User's age is:" + jedis.hget ("User", "age");

SYSTEM.OUT.PRINTLN ("Hash data for Redis storage: User's Sex:" + jedis.hget ("user", "sex")); ====hmset add multiple fields at once ======================================> System.out.println ("====hmset adds multiple fields at a time ============
		==========================> ");  Set Redis hash data ===> corresponding CMD terminal directive: Hset User (Key Name) value: (Name "Tom" Age three Sex "boy") map<string, string> HashMap
		= new hashmap<string, string> ();
		Hashmap.put ("name", "Lucy");
		Hashmap.put ("Age", "13");
		Hashmap.put ("Sex", "girl");
		Jedis.hmset ("User2", HashMap); Gets the stored data and outputs the instruction in the ===> corresponding CMD terminal: Hgetall User (key name) or: Hget User (key name) Name Field name System.out.println ("Redis The stored hash data is all derived hgetall:user2 as:"+ Jedis.hgetall (" user2 ")); /* Print: The hash data for Redis storage is all derived hgetall:user2: {sex=girl, age=13, name=lucy}*/list<string> rsmap = jedis.hmget ("User",
		"Name", "Age", "sex"); 
		System.out.println ("The hash data of Redis storage is all obtained hmget:user2:" +rsmap); /* Print: The hash data for Redis storage is all drawn hmget:user2: [Tom, boy]*/}/** * Java application Redis list (list) instance */public static void Ja
		Vauseredisbylist (Jedis Jedis) {System.out.println ("Order in reverse (advanced):====================================>");
		Store the data into the list in the ===> corresponding CMD terminal directive: Lpush llist1 (Key name) "1" (Value name) Jedis.lpush ("Llist1", "1");
		Jedis.lpush ("Llist1", "2");
	
		Jedis.lpush ("Llist1", "3"); Get the stored data and output the instructions in the ===> corresponding CMD terminal: Lrange llist1 (key name) list<string> Llist1 = Jedis.lrange ("Llist1", 0, 2);//
		Index range: 0,1,2 all out for (int i = 0; i < llist1.size (); i++) {System.out.println ("Redis list item Llist1:" + llist1.get (i)); }//==== ordered:====================================> System.out.println ("N/A (FIFO) Order: ======================= ============= ");
		Stores the data into the list of ===> corresponding to the cmd terminal in the instruction: Rpush rlist2 (Key name) "1" (Value name) Jedis.rpush ("Rlist2", "a");
		Jedis.rpush ("Rlist2", "B");
	
		Jedis.rpush ("Rlist2", "C"); Get the stored data and output the instructions in the ===> corresponding CMD terminal: Lrange rlist2 (key name) list<string> Rlist2 = Jedis.lrange ("Rlist2", 0, 2);//
		Index range: 0,1,2 all out for (int i = 0; i < rlist2.size (); i++) {System.out.println ("Redis list item Rlist2:" + rlist2.get (i)); }}/** * Java applies a set type (set) instance of Redis */private static void Javauseredisbyset (Jedis Jedis) {//Set up Redis s
		Et data ===> corresponds to CMD terminal directive: Sadd Set1 (Key name) "S1" (Value name) .... "S3" (value3 name) jedis.sadd ("Set1", "S1", "S2", "S3");
		Get the stored data and output the instructions in the ===> corresponding CMD terminal: Smembers Set1 (Key name) System.out.println ("Redis storage Set1 is:" + jedis.smembers ("Set1")); /* Print out of order: Redis storage Set1: [S3, S2, s1]*/}/** * Java application Redis All Keys instance */public static void Javauseredisgetkeys ( 
        Jedis Jedis) {//Get data and output set<string> keys = Jedis.keys ("*"); Iterator<string> It=keys.iterator ();   
            while (It.hasnext ()) {String key = It.next ();   
        System.out.println ("Redis key is named:" +key);
 }
		
	}
}

More detailed ways to do this see: using Jedis to operate Redis 6.Redis connection pooling in Java:

Package com.test;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;

Import Redis.clients.jedis.JedisPoolConfig;
    
    Public final class Redisutil {//redis server IP private static String ADDR = "192.168.0.100";
    
    The port number of the Redis private static int port = 6379;
    
    Access password private static String AUTH = "admin";
    The maximum number of available connection instances, the default value is 8, and//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 int max_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 int max_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 wait time is exceeded, the jedisconnectionexception is thrown directly; private static int max_wait = 10000;
    
    private static int TIMEOUT = 10000;
    
    Whether the validate operation is performed in advance when a Jedis instance is borrow, and if true, the resulting Jedis instance is available; private static Boolean test_on_borrow = true;
    
    private static Jedispool Jedispool = null; /** * Initializing Redis connection pool */static {TRy {jedispoolconfig config = new Jedispoolconfig ();
            Config.setmaxactive (max_active);
            Config.setmaxidle (Max_idle);
            Config.setmaxwait (max_wait);
            Config.settestonborrow (Test_on_borrow);
        Jedispool = new Jedispool (config, ADDR, PORT, TIMEOUT, AUTH);
        } catch (Exception e) {e.printstacktrace ();  }}/** * Get Jedis instance * @return * */public synchronized static Jedis Getjedis () {try
                {if (Jedispool! = null) {Jedis resource = Jedispool.getresource ();
            return resource;
            } else {return null;
            }} catch (Exception e) {e.printstacktrace ();
        return null;  }}/** * frees Jedis resources * @param Jedis */public static void Returnresource (final Jedis Jedis) {if (Jedis! = null) {Jedispool.returnresource (Jedis); }
    }
}



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.

Tags Index: