一、接口写法
namespace WebApplication1.Controllers.Redis
{[ApiController][Route("/api/[controller]")]public class RedisService : IRedisService{private readonly IConnectionMultiplexer _redis;//StackExchange.Redis库自带接口public RedisService(IConnectionMultiplexer redis){_redis = redis;}// 异步增加键值对[HttpPost("set")]public async Task<bool> SetAsync(string key, string value){var db = _redis.GetDatabase();bool result = await db.StringSetAsync(key, value);return result;}// 异步删除键值对[HttpDelete("remove")]public async Task<bool> RemoveAsync(string key){var db = _redis.GetDatabase();bool result = await db.KeyDeleteAsync(key);return result;}// 异步查询键值对[HttpGet("get")]public async Task<object> GetAsync(string key){var db = _redis.GetDatabase();var value = await db.StringGetAsync(key);if (value.HasValue){return new { Key = key, Value = value.ToString() };}return new { Message = $"Key {key} not found." };}// 异步清空所有缓存[HttpPost("flushall")]public async Task<bool> FlushAllAsync(){var server = _redis.GetServer("localhost", 6379); // 替换为你的 Redis 服务器 IP 和端口await Task.Run(() => server.FlushAllDatabases()); // 异步执行清空操作return true;}}
}
二、Startup.cs配置
public void ConfigureServices(IServiceCollection services)
{//省略其他代码// 注入自己写的服务实例services.AddTransient<IRedisService, RedisService>();// 配置 Redis 连接 (ConnectionMultiplexer 是 StackExchange.Redis自带的)var redisConnection = ConnectionMultiplexer.Connect("localhost:6379,defaultDatabase=1,allowAdmin = true"); // 替换成你实际的 Redis 连接字符串services.AddSingleton<IConnectionMultiplexer>(redisConnection);}