Detailed Advanced JAVA interview questions (b) - Redis (Distributed Lock, the lock reentrant, the cache data consistency, the cache penetration / puncture / Avalanche)

Detailed articles on Redis

Distributed Lock realize how redis

Use set (String key, String value, String nxxx, String expx, long time) method;
Method Parameter Description:

  • key lock key value is not too much to explain
  • value many students will ask to get hold of the lock also value doing? value to control who can be unlocked, or whether to re-lock the alignment reentrant.
  • nxxx can only take NX or XX:
    • NX set success when Key does not exist
    • XX When there is key set
  • pxex only take EX or PX: a data unit representing an expiration time, for describing the time field
    • EX in seconds
    • PX milliseconds
  • time expired time, the unit is the unit represented expx

Detailed method to return value: returns the string "OK" on behalf of success. Otherwise, insert failed

Light know this method is useless, because there is no process when the scene when the lock is occupied.
Also you need to set the spin and lock timeout.
How long is equivalent to trying to acquire a spin lock again,
the timeout is equivalent to how long after the spin still not successfully acquired lock is dropped

Setting a timeout hypothesis timeout = 10000 milliseconds per spin interval is 100 milliseconds
per spin timeout- = 100; when the timeout <= 0 end of the spin. code show as below

int timeout = 10000;
long expires = 60000L;
while(timeout >= 0) {
	if ("OK".equalsIgnoreCase(jedis.set(lockKey, lockValue, "NX", "PX", expires))) {
		return true;
	}
	timeout -= 100;
	Thread.sleep(100L);
}

Extended papers (leek classroom commenced it!)

There are a lot of blog writing distributed lock using setnx + expire method is wrong, because there is no guarantee the atomicity of the entire operation.
If the program suddenly crashes after performing setnx (), resulting in the lock is not set an expiration time. Then the deadlock will occur (has expired and will not be released).
Error Case Code:

if (1L == jedis.setnx(lockKey, lockValue)) {
	// 若在这里程序突然崩溃,则无法设置过期时间,将发生死锁
	jedis.expire(lockKey, expireTime);
}

How to achieve re-entry lock it?

First we look at what is reentrant lock

Reentrant lock to lock with the equivalent of a key, any thread may hold the key to unlock the corresponding locked and then again in the case of the lock has not been released.

After know the meaning of reentrant lock set according to the above method is not very easy to think of a solution?
Thinking: value set value of the above mentioned methods may be provided requestId (the UUID or other unique identifier), the thread-local variables stored requestId (ThreadLocal), when found in requestId removed (if present) to try and lock from being locked when ThreadLocal value comparison value, and if equal, returns true, re-set the expiration time.
Is not that to be here to complete the re-entry lock? However, it does not!
Reentrant lock must acquire repeated recording number of locks. Release the lock can not be deleted, because the lock is reentrant, if the lock to enter a number, a business executive in the inner end of the release lock out directly led to the implementation of external operations in the absence of lock cases, there safe question. Therefore, you must obtain a lock when the cumulative number of re-entry, then subtract the number of re-entry upon release, if reduced to 0, you can remove the lock.

How do the data cache and database consistency it

Data consistency which is a must in case of a write operation only need to ensure that, if all read naturally not appear inconsistent:
Program: First modify the database and then delete Redis cache, and the cache is generally required to set up failure time, to avoid inconsistencies in extreme cases.

Why choose Delete instead of directly modifying? Why should delete database write on the back instead of the front?

  • Select Delete instead of directly modifying
    if thread A write operation is performed at high concurrency, successfully update the database;
    this time thread B is also performed and thread A same operation, but in the process thread A executes updating the cache, the thread B updated the new database data into the cache;
    after all is done in a thread a thread B only relatively old data and updates to the cache; when this happens it leads to inconsistent data cache and database issues.
  • What should delete database write on the back rather than the front
    because if there is a thread to delete the query will update the old data into the database data inconsistency problem occurs before the cache has not been successfully written to the database.

Cache penetration, breakdown caching, caching solutions avalanche

Cache penetration

  • Glossary: ​​a key user wants to query data and found no redis memory, then check the database, the database did not. When a large number of requests to check this key time will cause great pressure on the persistence layer, which is to penetrate the cache
  • Solution:
    1, empty the cache object in the database does not have to redis save it, and set an expiration time exist.
    2, Bloom filter, all the parameters may be stored in a hash query form, when the user wants to query using Bloom filters found in (or define their own validation rules) is not set, discards the longer the persistence layer query.

Cache breakdown

  • Glossary: ​​is a key very hot, non-stop carrying large concurrency, concurrent large centralized access to this point, the moment when the key failure, complicated by ongoing large cache wore out, direct requests to the database, cause the database to pressure surge.
  • Solution:
    1, hot key never expires
    2, mutex, go get the query cache if the key is not present, if the acquisition went to check into the database, the results found in the write cache, if not get to lock in a certain time then to get the cache.

Cache avalanche

  • Glossary: ​​cache a large number of failures in a short time or redis suddenly hung up, leading to database queries pressure surge, resulting in the storage layer will hang.
  • Solution:
    1, redis redis availability since it is possible to hang up, then I'm more than a few additional redis, the other can continue to work after such a hang, in fact, it is to build clusters.
    2, mutex (ibid.)
    3, set different expiry time for the point in time of a cache miss as even as possible.

You talk to the young man finally redis clusters, so we what to talk about issues related to redis clusters it, ask interview questions to ask along the way thing are not you or the interviewer will not they change direction. So the basic answer to your next question might mean from your answer.
My next cluster then finishing it.

Published 18 original articles · won praise 45 · views 110 000 +

Guess you like

Origin blog.csdn.net/zhibo_lv/article/details/105203257