官方网站:Redis
Redis下载地址:Releases · tporadowski/redis · GitHub。
Redis可视化工具 Redis Desktop Manager
一、下载 Redis Desktop Manager
百度网盘:redis-desktop-manager-0.8.8.384.exe
文件名称:redis-desktop-manager-0.8.8.384.exe
开发:
1.在NuGet中引用:Microsoft.Extensions.Caching.StackExchangeRedis
2.在AppSetting.json中配置Redis连接字符串RedisConnection
{
"ConnectionStrings": {
"RedisConnection": "127.0.0.1:6379"
}
}
3.在Program中注册服务
//注册Redis服务
builder.Services.AddSingleton<IConnectionMultiplexer>(opt =>
ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("RedisConnection")));
4.在客户端使用Redis,设置缓存
using StackExchange.Redis;
using System.Reflection.Metadata;
using System.Text.Json;
using WebApplication1.Models;
namespace WebApplication1.Data
{
public class RedisPlatformRepo : IPlatformRepo
{
private IConnectionMultiplexer _redis;
//依赖注入连接复用
public RedisPlatformRepo(IConnectionMultiplexer redis)
{
_redis = redis;
}
//创建Redis键值对
public async Task createPlatform(Platform plat)
{
if (plat == null)
{
throw new ArgumentNullException(nameof(plat));
}
var db = _redis.GetDatabase();//得到Redis数据库
var serialPlat = JsonSerializer.Serialize(plat);
await db.StringSetAsync(plat.Id, serialPlat);//设置字符串类型的键值对
await db.SetAddAsync("MyKey", serialPlat);//设置集合类型的键值对
}
//得到集合类型的值
public async Task<IEnumerable<Platform?>?> GetAllPlatforms()
{
var db = _redis.GetDatabase();
var completeSet = await db.SetMembersAsync("MyKey");//读取集合类型
if (completeSet.Length > 0)
{
var obj = Array.ConvertAll(completeSet, val => JsonSerializer.Deserialize<Platform>(val)).ToList();
return obj;
}
return null;
}
//得到字符串类型的值
public async Task<Platform?> GetPlatformById(string id)
{
var db = _redis.GetDatabase();
string strPlatform = await db.StringGetAsync(id);
if (string.IsNullOrEmpty(strPlatform) == false)
{
Platform platform = JsonSerializer.Deserialize<Platform>(strPlatform);
return platform;
}
else
{
return null;
}
}
//创建Hash类型的键值对
public async Task CreateHashPlatform(Platform plat)
{
if (plat == null)
{
throw new ArgumentNullException(nameof(plat));
}
var db = _redis.GetDatabase();//得到Redis数据库
var serialPlat = JsonSerializer.Serialize(plat);
//设置Hash类型的键值对
await db.HashSetAsync("hashplatform", new HashEntry[]
{ new HashEntry(plat.Id,serialPlat) });
}
//得到Hash类型的值
public async Task<IEnumerable<Platform?>?> GetHashAllPlatforms()
{
var db = _redis.GetDatabase();
var completeHash = await db.HashGetAllAsync("hashplatform");//读取Hash类型
if (completeHash.Length > 0)
{
var obj = Array.ConvertAll(completeHash, val => JsonSerializer.Deserialize<Platform>(val.Value)).ToList();
return obj;
}
return null;
}
//得到Hash类型中的一个键值
public async Task<Platform?> GetHashPlatformById(string id)
{
var db = _redis.GetDatabase();
string strPlatform = await db.HashGetAsync("hashplatform", id);
if (string.IsNullOrEmpty(strPlatform) == false)
{
Platform platform = JsonSerializer.Deserialize<Platform>(strPlatform);
return platform;
}
else
{
return null;
}
}
}
}