4. [series] Redis Redis is an advanced application - Latency Queuing

Original: 4. [series] Redis Redis is an advanced application - Latency Queuing

We are accustomed to rabbitmq and kafka as messaging middleware, to increase the ability to asynchronously between applications. But used the students know, the use of professional messaging middleware to use very complex, we realize a simple function requires extensive operation. With redis, let me freed, using redis can very easily get, Redis message queue is not a professional messaging middleware, not very advanced features, if the pursuit of high reliability of the message, then the redis messaging middleware may not be suitable.

Asynchronous message queue

Redis list can be used to process the message queue, and using rpush lpush operation queues, and with lpop rpop for operating the queue.

> rpush notify-queue apple banana pear
(integer) 3
> llen notify-queue
(integer) 3
> lpop notify-queue
"apple"
> llen notify-queue
(integer) 2
> lpop notify-queue
"banana"
> llen notify-queue
(integer) 1
> lpop notify-queue
"pear"
> llen notify-queue
(integer) 0
> lpop notify-queue
(nil)

The above operation queue is used.

How do queue is empty

Pop client data obtained by the processing is completed, and then acquires the new data from the queue, so on ad infinitum. This is a queue consumer life cycle.

But how to do if the queue is empty, the client will be caught in an endless loop of pop. Non-stop pop, there is no data, and then pop. This is a waste of empty polling life. Empty polling not only pushed up the client's cpu, redis of QPS will be pulled. So how to do it

Improved 1: Normally thread to rest 1s, were pulled after waking up. Cpu not only the client can come down, Redis of QPS can drop down.

Thread.sleep(1000)  #JAVA 
Queuing delay

The above allows the client to sleep one second, even though it can solve some problems, but sleep can lead to delayed messages. If the single-threaded thread to sleep 1s delay is 1s, if multiple clients it?

Is there any better way to solve this problem?

Of course, and may be used blpop brpop, i.e. blocking read, will enter the sleep state without clogging read data, the data is immediately activated, delayed message is almost zero.

Empty automatic disconnection

If the thread has been blocked where the client connection became idle connection idle for too long, the server will automatically disconnect in general, reduce idle resource utilization, and this time blpop brpo will throw an exception to, especially when writing code Note also try again.

Lock conflicts

If the lock is not successful, it can generally be handled by lock failure in Strategy 3:
1. Direct throw an exception to notify the user try again later. This is generally for direct user requests.
A retry will 2.sleep
3 is transferred to the request queue delay, try again after a while

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12515046.html
Recommended