live-forum/server/webapi/LiveForum/ls/Redis配置说明.md
2026-03-24 11:27:37 +08:00

126 lines
3.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Redis服务自动注入配置说明
## 概述
本项目已成功配置Redis服务的自动注入可以通过依赖注入的方式在任意服务中使用Redis缓存功能。
## 配置内容
### 1. NuGet包依赖
已添加以下Redis相关包
- `Microsoft.Extensions.Caching.StackExchangeRedis` (8.0.0)
- `StackExchange.Redis` (2.7.20)
### 2. 配置文件 (appsettings.json)
```json
{
"ConnectionStrings": {
"Redis": "localhost:6379"
},
"Redis": {
"Configuration": "localhost:6379",
"InstanceName": "LiveForum"
}
}
```
### 3. 服务注册 (Program.cs)
- 使用`AddStackExchangeRedisCache`注册Redis缓存服务
- 在Autofac容器中注册`IRedisService`接口和`RedisService`实现
### 4. 服务接口和实现
- **接口**: `LiveForum.IService.IRedisService`
- **实现**: `LiveForum.Service.RedisService`
## 使用方法
### 在控制器中注入使用
```csharp
public class YourController : ControllerBase
{
private readonly IRedisService _redisService;
public YourController(IRedisService redisService)
{
_redisService = redisService;
}
public async Task<IActionResult> SomeAction()
{
// 设置缓存
await _redisService.SetAsync("key", "value", TimeSpan.FromMinutes(30));
// 获取缓存
var value = await _redisService.GetAsync("key");
// 设置对象缓存
var user = new { Id = 1, Name = "张三" };
await _redisService.SetAsync("user:1", user, TimeSpan.FromHours(1));
// 获取对象缓存
var cachedUser = await _redisService.GetAsync<object>("user:1");
return Ok();
}
}
```
### 在服务类中注入使用
```csharp
public class UserService : IUserService
{
private readonly IRedisService _redisService;
public UserService(IRedisService redisService)
{
_redisService = redisService;
}
public async Task<User> GetUserAsync(int userId)
{
var cacheKey = $"user:{userId}";
// 先尝试从缓存获取
var cachedUser = await _redisService.GetAsync<User>(cacheKey);
if (cachedUser != null)
{
return cachedUser;
}
// 缓存未命中,从数据库获取
var user = await GetUserFromDatabase(userId);
// 存入缓存
await _redisService.SetAsync(cacheKey, user, TimeSpan.FromMinutes(30));
return user;
}
}
```
## API测试接口
项目已包含`RedisTestController`控制器,提供以下测试接口:
- `POST /api/RedisTest/set-string` - 设置字符串缓存
- `GET /api/RedisTest/get-string/{key}` - 获取字符串缓存
- `POST /api/RedisTest/set-object` - 设置对象缓存
- `GET /api/RedisTest/get-object/{key}` - 获取对象缓存
- `DELETE /api/RedisTest/remove/{key}` - 删除缓存
- `GET /api/RedisTest/exists/{key}` - 检查缓存是否存在
- `PUT /api/RedisTest/set-expiration` - 设置缓存过期时间
## 注意事项
1. **Redis服务器**: 确保Redis服务器正在运行默认连接地址为`localhost:6379`
2. **连接字符串**: 可根据实际环境修改`appsettings.json`中的Redis连接配置
3. **序列化**: 对象缓存使用JSON序列化确保对象可序列化
4. **异常处理**: Redis服务包含完整的异常处理和日志记录
5. **性能**: Redis服务使用`InstancePerLifetimeScope`生命周期适合Web应用场景
## 扩展功能
如需更高级的Redis功能如获取TTL、批量操作等可以考虑
1. 直接使用`StackExchange.Redis`的`IDatabase`接口
2. 扩展`IRedisService`接口添加更多方法
3. 实现Redis分布式锁等功能