当前位置:网站首页>Redis(一)原理与基本使用
Redis(一)原理与基本使用
2022-06-25 09:37:00 【@@Mr.Fu】
一、Redis的核心概念
概念
Redis就是分布式缓存,也可以理解成进程外的缓存。
如图:

二、Redis的应用场景
应用场景
主要是应用在集群系统中。
单体项目就没必要用分布式缓存,使用本地缓存就可以;如图:

当客户端发起请求到系统,系统先去到本地缓存查询数据,没有查询到数据则到数据库查询,将查到的数据保存到本地缓存在返回到客户端;当第二次请求到系统,系统先去到本地缓存查询数据,则将缓存中的数据返回到客户端【第一次请求已经将数据保存到本地缓存中】;那他本地缓存的命中率为 50%;
使用本地缓存做分布式会有缓存命中率下降缺陷;如图:

客户端发起请求到Nginx,Nginx将请求代理到系统1,系统1查看本地缓存没有符合条件的数据,再到数据库获取数据存到本地缓存再返回到客户端;当客户端在一次发起请求到Nginx,Nginx将请求代理到系统2,系统2查看本地缓存没有符合条件的数据,再到数据库获取数据存到本地缓存再返回到客户端,那么发起了两次请求都没有到本地缓存中获取到数据,那它缓存命中率为 0/2=0;缓存命中率下降那就表明整体查询性能下降。
解决缓存命中率的方案
将缓存数据集中到一起,使用Redis分布式缓存,如图:

三、Redis的项目落地
条件
Demo项目
Redis 【在linux中部署】
Linux安装
#安装 wget 命令 yum -y install wget #下载 wget http://download.redis.io/releases/redis-6.2.6.tar.gz #解压 tar xzf redis-6.2.6.tar.gz #进入解压文件夹 cd redis-6.2.6 #安装 gcc yum install gcc #编译 make #进入解压后的src目录,运行服务 src/redis-server
Demo 项目配置
步骤
安装Redis Nuget包
StackExchange.Redis定义一个扩展类
public static IServiceCollection AddRedis(this IServiceCollection serviceCollection) { ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect("IP:端口"); serviceCollection.AddSingleton(connectionMultiplexer); return serviceCollection; }StateUp类注册【写了个扩展方法】
services.AddRedis();Redis 存储和获取
//注入 public readonly ConnectionMultiplexer connectionMultiplexer; public HomeController(ConnectionMultiplexer _connectionMultiplexer) { connectionMultiplexer = _connectionMultiplexer; } // 获取Redis值 obj = connectionMultiplexer.GetDatabase(0).StringGet(Key).ToString(); //存储Redis值 Key:Value connectionMultiplexer.GetDatabase(0).StringSet(Key, Value);Redis 存储集合
//获取Redis是否存在 RedisValue[] redisValues = connectionMultiplexer.GetDatabase(0).SetMembers("list"); //Redis中不存在此数据 if (redisValues.Length == 0) { //数据库中获取 list = demoDbContext.Set<User>().ToList(); List<RedisValue> rvList = new List<RedisValue>(); foreach (User user in list) { obj = JsonConvert.SerializeObject(user); rvList.Add(obj); } //将数据添加到Redis中 connectionMultiplexer.GetDatabase(0).SetAdd("list", rvList.ToArray()); }Redis Hash字典存储
使用场景:对数据库某个字段做修改或者某个int字段数据加一
//获取HASH字段中的数据 connectionMultiplexer.GetDatabase(0).HashGet(类型, key).ToString(); if (string.IsNullOrEmpty(obj)) { //到数据库获取数据 u = demoDbContext.Set<User>().Where(p => p.useid == useid).FirstOrDefault(); //将数据添加到Redis Hash字典中 connectionMultiplexer.GetDatabase(0).HashSet(类型, key,Value); //设置过期时间 connectionMultiplexer.GetDatabase(0).KeyExpire(类型,TimeSpan.FromSeconds(10)); } //字典中的Value值加1 connectionMultiplexer.GetDatabase(0).HashIncrement(类型, key);Redis 事务
//查询获取值 connectionMultiplexer.GetDatabase(0).HashGet(类型, key).ToString(); //创建事务 ITransaction transaction = connectionMultiplexer.GetDatabase(0).CreateTransaction(); //添加值 transaction.HashSetAsync(类型, key, value); //修改值 // transaction.HashSetAsync(类型, key,修改后Value); //提交事务 bool commit = transaction.Execute();Redis 批量存储数据
//创建批量对象 var bach = connectionMultiplexer.GetDatabase(0).CreateBatch(); //获取数据 List<User> list = new List<User>(); list = demoDbContext.user.ToList(); //批量添加 for (int i = 0; i < list.Count; i++) { bach.HashSetAsync("bach_User_"+i, "state", list[i].usestate); } //数据提交 bach.Execute();Redis集合排序
//获取数据 RedisValue[] rv = connectionMultiplexer.GetDatabase(0).SetMembers("User"); 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); //数据排序 connectionMultiplexer.GetDatabase(0).SortedSetAdd("User", data, u.usestate); // User :key data:Value值 u.usestate:排序字段 升序 }Redis分页查询
List<User> list = new List<User>(); //获取分页数据 100为行数,1为页数 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); } //添加数据到Redis中 connectionMultiplexer.GetDatabase(0).SetAdd("User", rvList.ToArray()); }
四、Redis的通信原理
Redis处理事件的简单模型:多路复用机制【一个线程处理多个连接】【订阅发布机制】;
原理
默认通过Socket协议建立连接的,服务端通过Socket的经过四层,在通过链路层再经过四层到达Redis建立连接;链路层【硬件层面】收到请求后,操作系统【生产者】通过同步转换成异步将请求发给事件收集器【MQ】然后Redis【订阅者】用一个线程通过轮询的方式处理事件,这就是多路复用机制。
Redis做的三件事:
1、建立连接
2、存储数据到本地缓存
3、持久化数据到文件中(开启新线程)
如图:

五、Redis的数据结构原理
原理
Redis 建立连接后,通过接口将数据存储到内存中。
如图:

数据持久化
目的
为了防止数据丢失。默认存放在AOP 文件中。
Redis Set原理图
数组+HASH表,如图:

HASH的作用:防止数据重复,使用HASH碰撞。
Redis HASH字典原理
数组+HASH表+单项列表。
原理
字典存储的字段经过hash得到一个数组的索引,根据索引将key \ value存储到数组中,如果得到的索引已经存在key\value 了,不会覆盖掉,会形成一个单项链表的形式继续存储。
如图:

缺陷
完全基于内存,会导致内存溢出。不适合存储海量数据。
边栏推荐
- [MySQL learning notes 22] index
- Match a mobile number from a large number of mobile numbers
- Is it safe for Huatai Securities to open an account on it? Is it reliable?
- Jetpack compose layout (I) - basic knowledge of layout
- Huipay international permet au commerce électronique transfrontalier de devenir une plate - forme de paiement transfrontalière conforme!
- How to delete a blank page that cannot be deleted in word
- How to make a self-made installer and package the program to generate an installer
- Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
- 在指南针上面开股票账户好不好,安不安全?
- 富时A50开户什么地方安全
猜你喜欢

Chitubox micromake l3+ slicing software configuration correspondence

Huipay international permet au commerce électronique transfrontalier de devenir une plate - forme de paiement transfrontalière conforme!

Pytorch_Geometric(PyG)使用DataLoader报错RuntimeError: Sizes of tensors must match except in dimension 0.

Consul的基本使用与集群搭建

Wallys/MULTI-FUNCTION IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL

MongoDB的原理、基本使用、集群和分片集群

How to delete a blank page that cannot be deleted in word

字符串 最长公共前缀
![[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)](/img/ee/2b8aebc1c63902d4d85ff71fd45070.jpg)
[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)

Jetpack compose layout (II) - material components and layout
随机推荐
Jetpack compose layout (IV) - constraintlayout
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
[Ruby on rails full stack course] course directory
How do dating applets make millions a year? What is the profit model?
Data-driven anomaly detection and early warning of item C in the May 1st mathematical modeling competition in 2021
Neat Syntax Design of an ETL Language (Part 2)
Neat Syntax Design of an ETL Language (Part 2)
Arduino bootloader burning summary
8. Intelligent transportation project (1)
[shared farm] smart agriculture applet, customized development and secondary development of Kaiyuan source code, which is more appropriate?
2022 meisai question a idea sharing
Flutter dialog: cupertinoalertdialog
Pytorch_Geometric(PyG)使用DataLoader报错RuntimeError: Sizes of tensors must match except in dimension 0.
[matlab] image binarization (imbinarize function)
8、智慧交通项目(1)
2021mathorcupc topic optimal design of heat dissipation for submarine data center
What are the PMP scores?
An auxiliary MVP architecture project quick development library -mvpfastdagger
puzzle(019.2)六边锁
[buuctf.reverse] 121-125