Redis Learning Note Two

Source: Internet
Author: User

First, the business

A transaction in Redis is a collection of a set of commands. Commands in one transaction are either executed or not executed.

1. Introduction to Business

The principle of a transaction is to send a command for a transaction to Redis, and then let Redis execute the commands sequentially. Let's look at an example:

  

First, use the Multi command to tell REDIS: The following command I gave you belongs to the same transaction, you do not execute, but temporarily save it.

Then we send two set commands to implement the assignment, and we can see that Redis does not execute these commands, but instead returns queued that the two commands have entered the queue of transactions awaiting execution.

When all the commands that you want to execute in the same transaction are sent to Redis, use the EXEC command to tell Redis that all commands in the transaction queue waiting to be executed are executed sequentially in the order in which they were sent.

2. Error handling

What does Redis do when a command in a transaction fails to execute? Here are three things:

  case One : syntax error, the wrong command does not exist or the number of command arguments is incorrect

  

As you can see, following the Multi command executes three commands, the second and third commands have syntax errors, and Redis executes the return error after exec executes.

  Scenario two : Run error, which is an error that occurs when the command executes.

  

This error is not discovered by Redis until it is actually executed, so the commands in the transaction are accepted and executed by Redis, and other commands in the transaction continue to execute (including commands after the error command) if a command in the transaction runs out of error.

  Note : Redis transactions do not have the rollback functionality provided by the relational database.

3. Watch command

The watch command monitors one or more keys, and once one of the keys is modified or deleted, the subsequent transaction is not executed, and the monitoring continues to the EXEC command (but there is no guarantee that other customers will not modify this key value).

  

After the watch command is executed in the example above, the key value is modified before the transaction executes, so the command set username Xujian in the transaction is not executed, and the EXEC command returns an empty result.

Note: The EXEC command cancels the monitoring of all keys immediately after execution, and if you do not want to execute the commands in the transaction, you can use the Unwatch command to ensure that the execution of the next transaction is not affected.

Second, the survival time

In Redis, you can use the expire command to set the lifetime of a key, and Redis will automatically delete it after the time.

The expire command is used with the expire key seconds, where the seconds parameter represents the time of the Key's lifetime, in seconds. If you want to know how long a key is to be deleted, you can use the TTL command and the return value is the time remaining (in seconds) of the key. If you want to cancel the time-to-live setting for a key, you can use the persist command to restore it permanently.

  

Third, sort 1, ordered set

The common usage scenarios for ordered collections are big data sorting, such as game player leaderboards.

2. Sort command

The sort command sorts the list type, collection type, and ordered collection type keys, and can accomplish tasks similar to connection queries in the relational database.

To sort the list:

  

Sorting an ordered collection type ignores the fraction of the element and sorts only on the value of the element itself:

  

3. By parameter

The by parameter's syntax is "by reference key", where the reference key can be a string type key or a field of a hash type key. If the by parameter is provided, the sort command will no longer be sorted by the value of the element itself, instead the first "*" in the reference key is substituted for each element using the value of the element and the value is obtained, and the element is sorted according to the value:

  

4. Store parameters

By default, sort returns the sort results directly, and you can use the store parameter if you want to save the sort results.

Note: The time complexity of the sort command is O (N+MLOGM), where n represents the number of elements in the list (collection or ordered collection) to be sorted, and m represents the number of elements to return. When n is large, the sort command performs relatively poorly, and redis creates a container of length n before sorting to store the elements to be sorted. The following points should be noted when using sort in development:

1. Minimize the number of elements in the key to be sorted (make n as small as possible)

2. Use the limit parameter to get only the required data (make m as small as possible)

3. If the amount of data to be sorted is large, use the store parameter to cache the result if possible

IV. Notification of the message

In general, Message Queuing has two scenarios, a producer consumer pattern and a Publisher subscriber pattern. Message Queuing with both Redis scenarios can be implemented.

1. Producer Consumer Model

Producer production messages are put into the queue, and multiple consumers listen to the queue at the same time, and whoever grabs the message will take the message out of the queue, which can only be owned by a single consumer for each message.

The concrete way is to create a task queue, the producer actively lpush the message, and the consumer goes to rpop the data. However, there is a problem, that is, consumers need to proactively request data, periodic requests will lead to waste of resources. If it is possible to notify the consumer once a new message is queued, this requirement can be achieved with the help of the Brpop command. Brpop and Rpop commands are similar, the only difference is that when there are no elements in the list, the Brpop command blocks the connection until a new element is added.

Brpop Key Timeout

The Brpop command receives two parameters, the first parameter key is a key value, and the second parameter, timeout, is the time-out. When the Brpop command takes data, if the data is temporarily absent, the command blocks until the time-out is reached. If timeout is set to 0, it will wait indefinitely.

  

2. Publisher Subscriber mode

Publisher production messages are placed in the queue, and subscribers to multiple listening queues receive the same message.

The producer uses the following command to publish the message:

PUBLISH CHANNEL MESSAGE

Subscribers subscribe to the message with the following command, and after the subscribe command is executed, the client enters the subscription state, and the client in this state cannot use 4 commands other than commands that are part of the Publish/subscribe model. In addition, you can use subscribe channel1.1 channel1.2 ... Subscribe to multiple channels at the same time.

SUBSCRIBE CHANNEL

  

3. The Java-implemented Redis message queue

In Jedis, there are corresponding methods for subscribing and publishing, in order to transfer objects, the object needs to be serialized and encapsulated into strings for processing.

Below we want to implement three classes, a corresponding publish, a corresponding subscribe, a corresponding object to be passed the entity class:

Entity class:

Importjava.io.Serializable;/*** Entity class * Package message *@authorAdministrator **/ Public classMessageImplementsserializable{Private Static Final LongSerialversionuid = 1L; PrivateString title; PrivateString content;  PublicString GetTitle () {returntitle; }     Public voidSettitle (String title) { This. title =title; }     PublicString getcontent () {returncontent; }     Public voidsetcontent (String content) { This. Content =content; }}

Publish class:

ImportJava.io.ByteArrayOutputStream;ImportJava.io.ObjectOutputStream;ImportRedis.clients.jedis.Jedis;/*** Publisher, for posting messages *@authorAdministrator **/ Public classtestpub{ Public Static voidMain (string[] args) {Jedis Jedis=NewJedis ("127.0.0.1"); Try{Message Message=NewMessage (); Message.settitle ("Sports News"); Message.setcontent ("The famous NBA star Kobe Bryant retired!" "); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); ObjectOutputStream Oos=NewObjectOutputStream (BAOs);            Oos.writeobject (message); String MSG1= Baos.tostring ("Iso-8859-1"); Jedis.publish ("Foo", MSG1); } Catch(Exception e) {e.printstacktrace ();    } jedis.close (); }}

Subscribe class:

ImportJava.io.ByteArrayInputStream;ImportJava.io.ObjectInputStream;ImportRedis.clients.jedis.Jedis;ImportRedis.clients.jedis.JedisPubSub;/*** subscribers, to receive messages *@authorAdministrator **/ Public classtestsub{ Public Static voidMain (string[] args) {Jedis Jedis=NewJedis ("127.0.0.1"); Jedispubsub jedispubsub=Newjedispubsub () {@Override Public voidOnunsubscribe (String Channel,intsubscribedchannels) {} @Override Public voidOnsubscribe (String Channel,intsubscribedchannels) {} @Override Public voidOnpunsubscribe (String pattern,intsubscribedchannels) {} @Override Public voidOnpsubscribe (String pattern,intsubscribedchannels) {} @Override Public voidonpmessage (string pattern, string channel, String message) {} @Override  Public voidonMessage (String channel, String message) {Try{Bytearrayinputstream bis=NewBytearrayinputstream (Message.getbytes ("iso-8859-1"));
//This specifies that the character set encodes a string into a byte array where the character set needs to be consistent with the character set at the time of publicationObjectInputStream Ois =NewObjectInputStream (bis); Message Message2=(Message) ois.readobject (); System.out.println (Message2.gettitle ()+ "\ n" +message2.getcontent ()); } Catch(Exception e) {e.printstacktrace (); } finally { } } }; Jedis.subscribe (Jedispubsub,"Foo"); Jedis.close (); }}

The subscription operation is performed before the publisher publishes the message and executes the result:

  

V. References

1. Redis Getting Started Guide

Redis Learning Note Two

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.