CSharp-Single-EFCore/Bunny.Service/IService/Service/RedisOptionService.cs

110 lines
3.5 KiB
C#
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.

using Bunny.Common.Connect;
using Bunny.Dao.Entity.System;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace Bunny.Service.IService.Service;
public class RedisOptionService : IRedisOptionService
{
private readonly IDatabase _redisDatabase = RedisContext.RedisDatabase;
/// <summary>
/// 添加Redis中一个值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void AddStringValue(string key, string value)
{
_redisDatabase.StringSet(key, value);
}
/// <summary>
/// 查询字符串Key
/// </summary>
/// <param name="key"></param>
public string QueryStringKey(string key)
{
return _redisDatabase.StringGet(key).ToString();
}
/// <summary>
/// 添加时间限制的key
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void AddTimeRedisKey(string key, string value)
{
// 时间限制为 6 秒
_redisDatabase.StringSet(key, value, TimeSpan.FromSeconds(6.0));
}
/// <summary>
/// var keepTtl = false: 可选参数表示是否保留已存在键的过期时间。如果设置为true并且键已经设置了过期时间那么新设置的键将保留原有的过期时间。
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void AddTimeRedisKeyTtl(string key, string value)
{
// var keepTtl = false: 可选参数表示是否保留已存在键的过期时间。如果设置为true并且键已经设置了过期时间那么新设置的键将保留原有的过期时间。throw new NotImplementedException();
// keepTtl 默认是false 如果当前给这个key设置了过期时间但是这个key之前就有过期时间如果是false会覆盖原有的时间如果为true不覆盖原有的时间
_redisDatabase.StringSet(key, value, TimeSpan.FromSeconds(6.0), true);
}
/// <summary>
/// Redis存入JSON内容
/// </summary>
/// <returns></returns>
public string AddJson()
{
var post = new Post
{
PostId = 1,
Title = "存入JSON内容",
Content = "正在存入JSON内容"
};
var json = JsonConvert.SerializeObject(post);
_redisDatabase.StringSet("postKey", json);
return json;
}
/// <summary>
/// 删除Redis中key
/// </summary>
/// <param name="key"></param>
public void DeleteKey(string key)
{
_redisDatabase.StringGetDelete(key);
}
/// <summary>
/// Redis中的事务
/// </summary>
public string SetRedisCreateTransaction(string key, string value)
{
// 创建事务
var transaction = _redisDatabase.CreateTransaction();
// 向事务中添加操作
transaction.StringSetAsync(key, value, TimeSpan.FromSeconds(6.0));
transaction.StringSetAsync("key1", "value1", TimeSpan.FromSeconds(6.0));
// 执行事务
var committed = transaction.Execute();
return committed ? "事务执行成功!" : "事务执行失败!";
}
/// <summary>
/// Redis设置Hash值
/// </summary>
/// <param name="key"></param>
/// <param name="keyExpire"></param>
public void AddHashWithRedis(string key, double keyExpire)
{
_redisDatabase.HashSet(key, "key", "value");
// 设置过期时间为6秒
_redisDatabase.KeyExpire(key, TimeSpan.FromSeconds(keyExpire));
}
}