net core Web API 使用 Redis

1.新建 Web API api
2.新建 类库 Service 安装 StackExchange.Redis
2.1 Service中 新建 Redis文件夹,并创建 接口IRedisService和类 RedisSerivce

点击查看代码
public interface IRedisService{
//获取 Redis 缓存值
string GetValue(string key);
//获取值,并序列化
TEntity Get<TEntity>(string key);
//保存
bool Set(string key, object value, TimeSpan cacheTime);
//新增
bool SetValue(string key, byte[] value);
//判断是否存在
bool Get(string key);
//移除某一个缓存值
bool Remove(string key);
//全部清除
bool Clear();
}

2.2 RedisService 中 引用 using StackExchange.Redis

点击查看代码
public class RedisCacheManage : IRedisCacheManage
{
private readonly string redisConnectionString;
private volatile ConnectionMultiplexer redisConnection;
private readonly object redisConnectionLock = new object();
public RedisCacheManage() {
string redisCOnfiguration = "127.0.0.1:6379";//Appsetting.app(new string[] {"AppSettings","RedisCaching","ConnectionString" });
if (string.IsNullOrWhiteSpace(redisCOnfiguration)) {
throw new ArgumentException("redis config is empty!",nameof(redisCOnfiguration));
}
this.redisConnectionString = redisCOnfiguration;
this.redisConnection = GetRedisConnection();
}
/// <summary>
/// 核心代码,获取连接实例
/// 通过双if 夹lock的方式,实现单例模式
/// </summary>
/// <returns></returns>
private ConnectionMultiplexer GetRedisConnection()
{
//如果已经连接实例,直接返回
if (this.redisConnection != null && this.redisConnection.IsConnected)
{
return this.redisConnection;
}
//加锁,防止异步编程中,出现单例无效的问题
lock (redisConnectionLock)
{
if (this.redisConnection != null)
{
//释放redis连接
this.redisConnection.Dispose();
}
try
{
this.redisConnection = ConnectionMultiplexer.Connect(redisConnectionString);
}
catch (Exception)
{
throw new Exception("Redis服务未启用,请开启该服务");
}
}
return this.redisConnection;
}
public bool Clear()
{
bool res = true;
foreach (var endPoint in this.GetRedisConnection().GetEndPoints())
{
var server = this.GetRedisConnection().GetServer(endPoint);
foreach (var key in server.Keys())
{
res=redisConnection.GetDatabase().KeyDelete(key);
}
}
return res;
}
public bool Get(string key)
{
return redisConnection.GetDatabase().KeyExists(key);
}
public string GetValue(string key)
{
return redisConnection.GetDatabase().StringGet(key);
}
public TEntity Get<TEntity>(string key)
{
var value = redisConnection.GetDatabase().StringGet(key);
if (value.HasValue)
{
//需要用的反序列化,将Redis存储的Byte[],进行反序列化
return SerializeHelper.Deserialize<TEntity>(value);
}
else
{
return default(TEntity);
}
}
public bool Remove(string key)
{
return redisConnection.GetDatabase().KeyDelete(key);
}
public bool Set(string key, object value, TimeSpan cacheTime)
{
if (value != null)
{
//序列化,将object值生成RedisValue
return redisConnection.GetDatabase().StringSet(key, SerializeHelper.Serialize(value), cacheTime);
}
return false;
}
public bool SetValue(string key, byte[] value)
{
return redisConnection.GetDatabase().StringSet(key, value, TimeSpan.FromSeconds(120));
}
}

2.3 Service类库中 新建Helper文件夹并创建 SerializeHelper类

点击查看代码
public class SerializeHelper
{
/// <summary>
/// 序列化
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static byte[] Serialize(object item) {
string jsonString = JsonSerializer.Serialize(item);
return Encoding.UTF8.GetBytes(jsonString);
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static TEntity Deserialize<TEntity>(byte[] value) {
if (value == null)
{
return default(TEntity);
}
string JsonString = Encoding.UTF8.GetString(value);
return JsonSerializer.Deserialize<TEntity>(JsonString);
}
}

3.1 Web API progarm.sc 中依赖注入

builder.Services.AddSingleton<IRedisService, RedisService>();

3.2 Web API 新增API控制器 RedisController.cs

引入
Service.Redis;
Model.Models;

点击查看代码
private readonly IRedisCacheManage _iredisCacheManage;
public RedisController(IRedisCacheManage redisCacheManage) {
_iredisCacheManage = redisCacheManage;
}
[HttpGet]
public async Task<IActionResult> Redis(string id) {
id = "fas21fASdf2asdF";
var key = $"Redis{id}";
TUser user = new TUser();
user.NickName = "张三";
user.Avator = "/asjd/ajslf.jpg";
user.State = 0;
user.PassWord = "123456";
user.Account = "456789";
user.ID = id;
if (_iredisCacheManage.Get<object>(key) != null)
{
user = _iredisCacheManage.Get<TUser>(key);
}
else {
//查到对应数据,存入 redis 中
//...
_iredisCacheManage.Set(key, user, TimeSpan.FromHours(2));//缓存2小时
}
return Ok(user);
}
posted @   浅·笑  阅读(116)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示