1、安装redis
Redis在windows平台上不受官方支持,所以想要在window安装Redis就必须去下载windows提供的安装包。安装地址:https://github.com/tporadowski/redis/releases
2、在NueGet安装包
3、在appsettings.json文件里面添加Redis相关配置信息
"Redis": {
"Connection": "127.0.0.1:6379,password=foobared", //连接地址,端口号,密码
"InstanceName": "local", //实例名称
"DefaultDB": "8" //db8数据库
}
redis的密码,可在安装目录下找到redis.windows.conf文件打开查看
4、创建RedisHelper类,代码如下:
using StackExchange.Redis;
using System.Collections.Concurrent;
namespace WebApi.Redis
{
public class RedisHelper : IDisposable
{
//连接字符串
private string _connectionString;
//实例名称
private string _instanceName;
//默认数据库
private int _defaultDB;
private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)
{
_connectionString = connectionString;
_instanceName = instanceName;
_defaultDB = defaultDB;
_connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
}
/// <summary>
/// 获取ConnectionMultiplexer
/// </summary>
/// <returns></returns>
private ConnectionMultiplexer GetConnect()
{
return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
}
/// <summary>
/// 获取数据库
/// </summary>
/// <param name="configName"></param>
/// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
/// <returns></returns>
public IDatabase GetDatabase()
{
return GetConnect().GetDatabase(_defaultDB);
}
public IServer GetServer(string configName = null, int endPointsIndex = 0)
{
var confOption = ConfigurationOptions.Parse(_connectionString);
return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
}
public ISubscriber GetSubscriber(string configName = null)
{
return GetConnect().GetSubscriber();
}
public void Dispose()
{
if (_connections != null && _connections.Count > 0)
{
foreach (var item in _connections.Values)
{
item.Close();
}
}
}
}
}
5、在program.cs中添加依赖
//redis缓存
var section = builder.Configuration.GetSection("Redis");
//连接字符串
string _connectionString = section.GetSection("Connection").Value;
//实例名称
string _instanceName = section.GetSection("InstanceName").Value;
//默认数据库
int _defaultDB = int.Parse(section.GetSection("DefaultDB").Value ?? "0");
builder.Services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _defaultDB));
6、控制器中可用直接注入依赖使用
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;
using WebApi.Redis;
namespace WebApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly IDatabase _redis;
public TestController(RedisHelper redis) {
_redis = redis.GetDatabase();
}
[HttpGet]
public Person GetPerson()
{
string? name = _redis.StringGet("name");
return new Person(name, 18);
}
[HttpPost]
public string SavePerson(string name)
{
_redis.StringSet("name",name);
return "保存成功!" + name;
}
}
}