Caching mechanisms
explain : Using cache can effectively reduce the frequency of users accessing physical devices , Quickly remove data from memory , After returning to the user, you need to ensure that the data in memory is the database data .
1. The running environment of the cache should be in memory ( fast ).
2. Use C Language development cache .
3. Cached data structure 【K——V structure , It is generally used String There are many types ,hey Must be unique ,v:Json Format 】.
4. The memory environment is erased when it is powered down , So the memory data should be persisted ( Write disk operation ).
5. If the memory size is not maintained , It is easy to cause memory overflow , So using LRU Algorithm optimization !
Redis Introduce
redis It's a key-value The storage system . and Memcached similar , It supports storage value There are more types , Include string( character string )、list( Linked list )、set( aggregate )、zset(sorted set -- Ordered set ) and hash( Hash type ). These data types support push/pop、add/remove And take intersection, union and difference sets and more abundant operations , And these operations are Atomicity Of . On this basis ,redis Support various sorts of sorting . And memcached equally , To ensure efficiency , The data is cached in memory . The difference is redis Periodically, updated data is written to disk or changes are written to an appended log file , And on this basis to achieve master-slave( Master-slave ) Sync .
Redis It's open source (BSD The license ) Of , Data structure storage system in memory , It can be used as a database 、 Caching and message middleware . It supports multiple types of data structures , Such as character string (strings), hash (hashes), list (lists), aggregate (sets), Ordered set (sorted sets) And scope query , bitmaps, hyperloglogs and Geographical space (geospatial) Index radius query . Redis Built in Copy (replication),LUA Script (Lua scripting), LRU Driving events (LRU eviction), Business (transactions) And different levels of Disk persistence (persistence), And pass Redis sentry (Sentinel) And automatic Partition (Cluster) Provide high availability (high availability).
Atomicity States :
Redis Is a single process, single thread operation , So there is no thread concurrency security issue , In the way of queue, one operation at a time .
Redis Common use :
1.Redis It can be used as a cache .
2.Redis It can be used as a database ( Verification Code ....)
3.Redis It can be used as message middleware ( bank transfer ....)
Redis Installation
1. decompression Redis Installation package
[[email protected] src]# tar -zxvf redis-5.0.4.tar.gz
2. install Redis
explain : stay Redis Execute the command in the root directory of
command :
1."make"
2.make install
modify Redis Configuration file for
command set nu // Show line number
Change location :
~~~~1. notes IP binding
2. Turn off protection mode
3. Turn on background start
Redis Server command
1. Start command : redis-server redis.conf
2. Search command : ps -ef | grep redis
3. Enter the client : redis-cli -p 6379( If the default port is 6379 The port number here can be omitted )
4. close redis: kill -9 PID Number | redis-cli -p 6379 shutdown
Redis Introductory cases
introduce jar Package file
<!--spring Integrate redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
Editing tests API
public class TestRedis {
/**
* 1. test redis Whether the program connection is normal
* step :
* 1. Instantiation jedis Tools API object (host:port)
* 2. According to the example operation redis The method is to order
*
* The explanation about the link failure :
* 1. Check Linux A firewall
* 2. Check Redis Configuration file modification item
* 2.1 IP binding
* 2.2 Protected mode
* 2.3 Background start
* 3. Check redis Starting mode redis-server redis.conf
* 4. Check IP port And redis Whether to start ...
*/ @Test
public void test01(){
String host="192.168.126.129";
int port=6379;
Jedis jedis=new Jedis(host,port);
jedis.set("2006", " study hard and make progress every day ");
System.out.println(jedis.get("2006"));
// Does the exercise exist key
if(jedis.exists("2006")){
jedis.del("2006");
}else{
jedis.set("2006","hdsjiahjds");
jedis.expire("2006", 100);
}
}
setex Use
/**
* demand :
* 1. towards redis Insert data
* 2. by key Set the timeout .,60 Seconds after the failure
* 3. Threads sleep 3 second
* 4. obtain key The remaining survival time of
*
*/// If you use the following method, it will cause an exception, and the following code will not be executed , So to meet the requirements of atomicity
@Test
public void test02() throws InterruptedException {
Jedis jedis=new Jedis("192.168.126.129",6379);
jedis.set(" A dream of red mansions ", " Jia Baoling ");
jedis.expire(" A dream of red mansions ", 60);
Thread.sleep(3000);
System.out.println(jedis.ttl(" A dream of red mansions "));
}
/* If you use redis And when you need to add a timeout , In general, the atomic requirements should be met
* Atomicity : It's either a success or a failure , But it has to be done at the same time
* use setex complete redis The addition of ,setex Ensure atomic operation of data
* */
@Test
public void test03() throws InterruptedException {
Jedis jedis=new Jedis("192.168.126.129",6379);
jedis.setex(" A dream of red mansions ",60, " Lin daiyu ");
System.out.println(jedis.get(" A dream of red mansions "));
}
setnx Use
/**
* Determine whether the data already exists , If it already exists, do not modify , If not, add
*
* I used to use if Judgment statement to determine whether the data already exists ,
* Here with setnx Determine whether the data already exists
* */
@Test
public void test04() throws InterruptedException {
Jedis jedis=new Jedis("192.168.126.129",6379);
/*if(jedis.exists("aa")){
System.out.println("key Already exist , Don't modify ");
}else{ jedis.set("aa", " Test data ");
}*/ jedis.setnx("aaa", " Does the data exist ");
System.out.println(jedis.get("aaa"));
}
set Timeout atomic operation
/**
* demand :
* 1. When the user is asked to assign a value , If the data exists, no assignment is made . setnx
* 2. It is required that in the assignment operation , You have to set the timeout time , And it requires atomicity setex
* * If you want to meet both requirements, you can't use setnx and setex. Because these two methods are separate
* It's OK to execute , But if you put them together, you will make mistakes .
* So we need to use set Method , Inside params It means to set a set object .
* SetParams Parameters in :
* nx: Only when the data does not exist
* xx: The value is assigned when the data exists
* ex: Time of failure , The unit is seconds
* px: It also means the time of failure , In milliseconds
*/
@Test
public void test05(){
Jedis jedis=new Jedis("192.168.126.129",6379);
SetParams setParams=new SetParams();
setParams.nx().ex(60);// Lock operation
jedis.set("bbb", " Implement business operations ccc", setParams);
System.out.println(jedis.get("bbb")+jedis.ttl("bbb"));
jedis.del("bbb");// The operation of unlocking
}
List Set up exercises
@Test
public void testList() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129", 6379);
jedis.lpush("list", "1","2","3");
System.out.println(jedis.rpop("list"));
}
redis Transaction control
@Test
public void testTx() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129", 6379);
//1. Open transaction
Transaction transaction = jedis.multi();
try {
transaction.set("aa", "aa");
// Commit transaction
transaction.exec();
}catch (Exception e){
e.printStackTrace();
// Roll back the transaction
transaction.discard();
}
}