当前位置:网站首页>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 .
边栏推荐
- 广发证券靠谱吗?是否合法?开股票账户安全吗?
- x86的编码格式
- 链表 删除链表中的节点
- Free platform for wechat applet making, steps for wechat applet making
- Consul的基本使用与集群搭建
- 可穿戴设备或将会泄露个人隐私
- Redis(一)原理与基本使用
- SQL to object thinking vs SQL of object thinking
- How do wechat sell small commodity programs do? How to open wechat apps to sell things?
- Match a mobile number from a large number of mobile numbers
猜你喜欢

manhattan_slam环境配置

链表 删除链表中的节点

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

CYCA 2022少儿形体礼仪初级师资班 深圳总部站圆满结束

Etcd教程 — 第四章 Etcd集群安全配置

Nano data World Cup data interface, CSL data, sports data score, world cup schedule API, real-time data interface of football match

How much does a wechat applet cost? Wechat applet development and production costs? Come and have a look
![[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

x86电脑上下载debian的arm64的包

Creo makes a mobius belt in the simplest way
随机推荐
x86电脑上下载debian的arm64的包
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
What should be paid attention to in PMP examination?
SparseArray details
匯付國際為跨境電商賦能:做合規的跨境支付平臺!
Armbian version name comparison
Vscode attempted to write the procedure to a pipeline that does not exist
The problem of wirengpi program running permission
Fcpx quickly add subtitles | Final Cut Pro import fcpxml subtitle file does not match the video time? I got it in code
Grabcut image segmentation in opencv
ShardingSphere-Proxy 5.0 分库分表(一)
Jetpack compose layout (III) - custom layout
[Ruby on rails full stack course] course directory
js工具函数,自己封装一个节流函数
Redis(二)分布式锁与Redis集群搭建
Modbus协议与SerialPort端口读写
Kotlin advanced set
Reasons for Meiye to choose membership system
How to "transform" small and micro businesses (II)?
可穿戴设备或将会泄露个人隐私