当前位置:网站首页>Redis (I) principle and basic use
Redis (I) principle and basic use
2022-06-25 10:05:00 【@@Mr.Fu】
List of articles
One 、Redis Core concept of
Concept
Redis Distributed cache , It can also be understood as an out of process cache .
Pictured :

Two 、Redis Application scenarios of
Application scenarios
It is mainly used in cluster system .
There is no need to use distributed cache for single projects , Using local cache can ; Pictured :

When the client initiates a request to the system , The system first goes to the local cache to query the data , If no data is queried, query the database , Save the found data to the local cache and return to the client ; When the second request comes to the system , The system first goes to the local cache to query the data , The data in the cache is returned to the client 【 The first request has saved the data to the local cache 】; The hit rate of his local cache is 50%;
Using local cache to do distributed caching will have the defect of decreasing cache hit rate ; Pictured :

The client initiates a request to Nginx,Nginx Proxy requests to the system 1, System 1 Check that there is no qualified data in the local cache , Then go to the database to get the data, save it to the local cache, and then return it to the client ; When the client sends a request to Nginx,Nginx Proxy requests to the system 2, System 2 Check that there is no qualified data in the local cache , Then go to the database to get the data, save it to the local cache, and then return it to the client , Then, two requests are initiated and no data is obtained from the local cache , Then its cache hit rate is 0/2=0; If the cache hit rate decreases, it indicates that the overall query performance decreases .
Solution to cache hit rate
Bring together cached data , Use Redis Distributed cache , Pictured :

3、 ... and 、Redis Project implementation
Conditions
Demo project
Redis 【 stay linux Deployment in China 】
Linux install
# install wget command yum -y install wget # download wget http://download.redis.io/releases/redis-6.2.6.tar.gz # decompression tar xzf redis-6.2.6.tar.gz # Enter the unzip folder cd redis-6.2.6 # install gcc yum install gcc # compile make # Enter the src Catalog , Operation service src/redis-server
Demo Project configuration
step
install Redis Nuget package
StackExchange.RedisDefine an extension class
public static IServiceCollection AddRedis(this IServiceCollection serviceCollection) { ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect("IP: port "); serviceCollection.AddSingleton(connectionMultiplexer); return serviceCollection; }StateUp Class registration 【 Wrote an extension method 】
services.AddRedis();Redis Store and get
// Inject public readonly ConnectionMultiplexer connectionMultiplexer; public HomeController(ConnectionMultiplexer _connectionMultiplexer) { connectionMultiplexer = _connectionMultiplexer; } // obtain Redis value obj = connectionMultiplexer.GetDatabase(0).StringGet(Key).ToString(); // Storage Redis value Key:Value connectionMultiplexer.GetDatabase(0).StringSet(Key, Value);Redis Store collections
// obtain Redis Whether there is RedisValue[] redisValues = connectionMultiplexer.GetDatabase(0).SetMembers("list"); //Redis This data does not exist in if (redisValues.Length == 0) { // Get... In the database list = demoDbContext.Set<User>().ToList(); List<RedisValue> rvList = new List<RedisValue>(); foreach (User user in list) { obj = JsonConvert.SerializeObject(user); rvList.Add(obj); } // Add data to Redis in connectionMultiplexer.GetDatabase(0).SetAdd("list", rvList.ToArray()); }Redis Hash Dictionary storage
Use scenarios : Modify a field in the database or a int Add one to the field data
// obtain HASH The data in the field connectionMultiplexer.GetDatabase(0).HashGet( type , key).ToString(); if (string.IsNullOrEmpty(obj)) { // Get data from the database u = demoDbContext.Set<User>().Where(p => p.useid == useid).FirstOrDefault(); // Add data to Redis Hash In the dictionary connectionMultiplexer.GetDatabase(0).HashSet( type , key,Value); // Set expiration time connectionMultiplexer.GetDatabase(0).KeyExpire( type ,TimeSpan.FromSeconds(10)); } // In the dictionary Value It's worth adding 1 connectionMultiplexer.GetDatabase(0).HashIncrement( type , key);Redis Business
// Query to get the value connectionMultiplexer.GetDatabase(0).HashGet( type , key).ToString(); // Create transaction ITransaction transaction = connectionMultiplexer.GetDatabase(0).CreateTransaction(); // add value transaction.HashSetAsync( type , key, value); // Modified value // transaction.HashSetAsync( type , key, After modification Value); // Commit transaction bool commit = transaction.Execute();Redis Mass storage of data
// Create batch objects var bach = connectionMultiplexer.GetDatabase(0).CreateBatch(); // get data List<User> list = new List<User>(); list = demoDbContext.user.ToList(); // Batch addition for (int i = 0; i < list.Count; i++) { bach.HashSetAsync("bach_User_"+i, "state", list[i].usestate); } // Data submission bach.Execute();Redis Collection sorting
// get data RedisValue[] rv = connectionMultiplexer.GetDatabase(0).SetMembers("User"); if (rv.Length == 0) { list = demoDbContext.Set<User>().ToList(); List<RedisValue> rvList = new List<RedisValue>(); // Batch add data foreach (User u in list) { var data = JsonConvert.SerializeObject(u); rvList.Add(data); // Data sorting connectionMultiplexer.GetDatabase(0).SortedSetAdd("User", data, u.usestate); // User :key data:Value value u.usestate: Sort field Ascending }Redis Paging query
List<User> list = new List<User>(); // Get paging data 100 Is the number of rows ,1 Is the number of pages RedisValue[] rv = connectionMultiplexer.GetDatabase(0).SetScan("User",100,0,1).ToArray(); if (rv.Length == 0) { list = demoDbContext.Set<User>().ToList(); List<RedisValue> rvList = new List<RedisValue>(); foreach (User u in list) { var data = JsonConvert.SerializeObject(u); rvList.Add(data); } // Add data to Redis in connectionMultiplexer.GetDatabase(0).SetAdd("User", rvList.ToArray()); }
Four 、Redis The principle of communication
Redis A simple model for handling events : Multiplexing mechanism 【 One thread handles multiple connections 】【 Subscription publishing mechanism 】;
principle
Default by Socket Protocol to establish a connection , Server through Socket After four layers , After passing through the link layer, it will reach... Through four layers Redis Establishing a connection ; The link layer 【 Hardware level 】 Upon receipt of the request , operating system 【 producer 】 Send the request to the event collector through synchronous to asynchronous conversion 【MQ】 then Redis【 subscriber 】 Use a thread to process events through polling , This is the multiplexing mechanism .
Redis Three things to do :
1、 Establishing a connection
2、 Store data to local cache
3、 Persist data to a file ( Start a new thread )
Pictured :

5、 ... and 、Redis Principle of data structure
principle
Redis Once the connection is established , Store data in memory through the interface .
Pictured :

Data persistence
Purpose
To prevent data loss . Default store in AOP In file .
Redis Set Schematic diagram
Array +HASH surface , Pictured :

HASH The role of : Prevent data duplication , Use HASH Collision .
Redis HASH Dictionary principle
Array +HASH surface + Single item list .
principle
The fields stored in the dictionary go through hash Get the index of an array , Index according to key \ value Store in array , If the resulting index already exists key\value 了 , It won't cover , It will form a single linked list and continue to store .
Pictured :

defects
Completely based on memory , Can cause memory overflow . Not suitable for storing massive data .
边栏推荐
- Kotlin advanced - class
- vscode试图过程写入管道不存在
- The problem of wirengpi program running permission
- NFC read / write mode development - book summary
- 纳米数据世界杯数据接口,中超数据,体育数据比分,世界杯赛程api,足球比赛实时数据接口
- Wallys/MULTI-FUNCTION IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL
- Remittance international empowers cross-border e-commerce: to be a compliant cross-border payment platform!
- Minio基本使用与原理
- [smart agriculture program] smart agriculture small program project is currently popular.
- Remove the mosaic, there's a way, attached with the running tutorial
猜你喜欢

ScheduleMaster分布式任务调度中心基本使用和原理

字符串 实现 strStr()

22 mathematical modeling contest 22 contest C

Nano data World Cup data interface, CSL data, sports data score, world cup schedule API, real-time data interface of football match
![[matlab] image binarization (imbinarize function)](/img/3e/066f460d9f436bbc43ea35e46093e2.jpg)
[matlab] image binarization (imbinarize function)
![[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate](/img/75/a06e20b4394579cbd9f6d3a075907a.jpg)
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate

Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?

Consul的基本使用与集群搭建

Redis(二)分布式锁与Redis集群搭建
![[2020 cloud development + source code] 30 minutes to create and launch wechat applet practical project | zero cost | cloud database | cloud function](/img/89/39851fee714be872a599ad4ddd4852.jpg)
[2020 cloud development + source code] 30 minutes to create and launch wechat applet practical project | zero cost | cloud database | cloud function
随机推荐
[buuctf.reverse] 121-125
Puzzle (019.2) hexagonal lock
manhattan_ Slam environment configuration
Mysql 源码阅读(二)登录连接调试
可穿戴设备或将会泄露个人隐私
Armbian version name comparison
Redis(二)分布式锁与Redis集群搭建
How to "transform" small and micro businesses (II)?
Cocopod error failed: undefined method `map 'for nil:nilclass
51 SCM time stamp correlation function
Is it harder to find a job in 2020? Do a good job in these four aspects and find a good job with high salary
ScheduleMaster分布式任务调度中心基本使用和原理
使用EVO
Methodchannel of flutter
The way that flutter makes the keyboard disappear (forwarding from the dependent window)
The gradle configuration supports the upgrade of 64 bit architecture of Xiaomi, oppo, vivo and other app stores
ShardingSphere-Proxy 4.1 分库分表
MySQL create given statement
Notes on writing questions in C language -- monkeys eat peaches
CyCa 2022 children's physical etiquette primary teacher class Shenzhen headquarters station successfully concluded