Redis集群概述
Redis集群是由多个Redis实例组成的集合,能够有效解决系统的高并发问题。
Redis集群架构图
架构图解释:
1、6个Redis实例
2、3个主节点(master实例)和3个从节点(slave实例)
3、使用 redis-trib.rb 搭建Redis集群
Redis集群部署
准备工作
1、准备redis
下载地址:https://github.com/MicrosoftArchive/redis/releases
a、创建6个redis实例
创建6个 redis.windows.conf:
redis.6380.conf,redis.6381.conf,redis.6382.conf,redis.6383.conf
redis.6384.conf,redis.6385.conf
每个文件的配置如下,除端口号外其它配置相同:
port 6380 #端口号
bind 127.0.0.1 #IP地址
appendonly yes #数据的保存为aof格式
appendfilename "appendonly.6380.aof" #数据保存文件
cluster-enabled yes #是否开启集群
cluster-config-file nodes.6380.conf #集群节点配置文件
cluster-node-timeout 15000 #节点超时时间
cluster-slave-validity-factor 10 #验证slaver节点次数
cluster-miqration-barrier 1
cluster-require-full-coverage yes #master节点和slaver节点之间是否全量复制
将六个文件放入Redis解压目录中:
b. 启动6个Redis实例
redis-server.exe redis.6380.conf
redis-server.exe redis.6381.conf
redis-server.exe redis.6382.conf
redis-server.exe redis.6383.conf
redis-server.exe redis.6384.conf
redis-server.exe redis.6385.conf
2、创建Redis集群
a. 安装redis-trib.rb环境
下载地址:https://rubyinstaller.org/downloads/
安装教程
b. 安装Redis驱动redis-3.2.2.gem
下载地址:http://rubygems.org/downloads/redis-3.3.5.gem
安装命令:
gem install --local D:\Redis\redis-cluster\redis-3.3.5.gem
# 打开D:\Redis\redis-cluster\ruby\bin路径下的cmd,粘贴上面的命令并回车
安装成功显示:
搭建步骤
下载redis-trib.rb:https://github.com/beebol/redis-trib.rb
使用create命令创建集群:
#使用create创建
create host1:port1 ... hostN:portN
redis-trib.rb create --replicas 1 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384 127.0.0.1:6385
#
显示集群安装成功
客户端验证
电商项目实战
前提:
1、创建电商系统:创建ASP.NET Core WebAPI项目
2、创建添加商品业务场景
a、在NuGet包中安装 Microsoft.Extensions.Caching.StackExchangeRedis
#NuGet包中安装:
Microsoft.Extensions.Caching.StackExchangeRedis
b、配置Microsoft.Extensions.Caching.StackExchangeRedis
builder.Services.AddStackExchangeRedisCache(options => {
options.Configuration = "127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384,127.0.0.1:6385";
});
c. 使用缓存
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
namespace Test_Redis_WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
private readonly ILogger<ProductController> _logger;
private readonly IDistributedCache _cache;
/// <summary>
/// 构造方法
/// </summary>
public ProductController(ILogger<ProductController> logger, IDistributedCache cache)
{
this._logger = logger;
_cache = cache;
}
// POST api/<AddProduct>
[HttpGet("AddProduct")]
public IActionResult AddProduct(string productName)
{
// 尝试从缓存中获取数据
var cachedData = _cache.GetString("myCacheKey");
if (cachedData == null)
{
// 将数据添加到缓存中
var cacheEntryOptions = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(10)); // 设置滑动过期时间
_cache.SetString("myCacheKey", productName, cacheEntryOptions);
return Ok("添加成功");
}
return Ok("添加成功");
}
}
}
结果