.net core3.1 Redis使用

1.下载客户端https://github.com/MSOpenTech/redis/releases。安装客户端https://www.runoob.com/redis/redis-install.html
2.参考https://www.cnblogs.com/LiChen19951127/p/10478153.html
3.自己运行
①Nuget安装 StackExchange.Redis
②redishelper
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

using StackExchange.Redis;
using Newtonsoft.Json;

namespace WebApplication1
{
public class RedisHelperNetCore
{
//单例模式
public static RedisCommon Default { get { return new RedisCommon(); } }
public static RedisCommon One { get { return new RedisCommon(1, “127.0.0.1:6379”); } }
public static RedisCommon Two { get { return new RedisCommon(2, “127.0.0.1:6379”); } }
}
///
/// Redis操作类
/// 老版用的是ServiceStack.Redis。
/// Net Core使用StackExchange.Redis的nuget包
///
public class RedisCommon
{
//public static ILogger Log = UtilLogger.Log;//日志记录
//redis数据库连接字符串
private string _conn = AppConfigurtaionServices.Configuration[“RedisConfig:ReadWriteHosts”] ?? “127.0.0.1:6379”;
private int _db = 0;
//静态变量 保证各模块使用的是不同实例的相同链接
private static ConnectionMultiplexer connection;
public RedisCommon() { }
///
/// 构造函数
///
///
///
public RedisCommon(int db, string connectStr)
{
_conn = connectStr;
_db = db;
}
///
/// 缓存数据库,数据库连接
///
public ConnectionMultiplexer CacheConnection
{
get
{
try
{
if (connection == null || !connection.IsConnected)
{
connection = new Lazy(() => ConnectionMultiplexer.Connect(_conn)).Value;
}
}
catch (Exception ex)
{
//Log.LogError(“RedisHelper->CacheConnection 出错\r\n” + ex.ToString());
return null;
}
return connection;
}
}
///
/// 缓存数据库
///
public IDatabase CacheRedis => CacheConnection.GetDatabase(_db);

    #region --KEY/VALUE存取--
    /// 
    /// 单条存值
    /// 
    /// key
    /// The value.
    /// true if XXXX, false otherwise.
    public bool StringSet(string key, string value)
    {
        return CacheRedis.StringSet(key, value);
    }
    /// 
    /// 保存单个key value
    /// 
    /// Redis Key
    /// 保存的值
    /// 过期时间
    /// 
    public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?))
    {
        return CacheRedis.StringSet(key, value, expiry);
    }
    /// 
    /// 保存多个key value
    /// 
    /// key
    /// 
    public bool StringSet(KeyValuePair[] arr)
    {
        return CacheRedis.StringSet(arr);
    }
    /// 
    /// 批量存值
    /// 
    /// key
    /// The value.
    /// true if XXXX, false otherwise.
    public bool StringSetMany(string[] keysStr, string[] valuesStr)
    {
        var count = keysStr.Length;
        var keyValuePair = new KeyValuePair[count];
        for (int i = 0; i < count; i++)
        {
            keyValuePair[i] = new KeyValuePair(keysStr[i], valuesStr[i]);
        }

        return CacheRedis.StringSet(keyValuePair);
    }

    /// 
    /// 保存一个对象
    /// 
    /// 
    /// 
    /// 
    /// 
    public bool SetStringKey(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
    {
        string json = JsonConvert.SerializeObject(obj);
        return CacheRedis.StringSet(key, json, expiry);
    }
    /// 
    /// 追加值
    /// 
    /// 
    /// 
    public void StringAppend(string key, string value)
    {
        ////追加值,返回追加后长度
        long appendlong = CacheRedis.StringAppend(key, value);
    }

    /// 
    /// 获取单个key的值
    /// 
    /// Redis Key
    /// 
    public RedisValue GetStringKey(string key)
    {
        return CacheRedis.StringGet(key);
    }
    /// 
    /// 根据Key获取值
    /// 
    /// 键值
    /// System.String.
    public string StringGet(string key)
    {
        try
        {
            return CacheRedis.StringGet(key);
        }
        catch (Exception ex)
        {
            //Log.LogError("RedisHelper->StringGet 出错\r\n" + ex.ToString());
            return null;
        }
    }

    /// 
    /// 获取多个Key
    /// 
    /// Redis Key集合
    /// 
    public RedisValue[] GetStringKey(List listKey)
    {
        return CacheRedis.StringGet(listKey.ToArray());
    }
    /// 
    /// 批量获取值
    /// 
    public string[] StringGetMany(string[] keyStrs)
    {
        var count = keyStrs.Length;
        var keys = new RedisKey[count];
        var addrs = new string[count];

        for (var i = 0; i < count; i++)
        {
            keys[i] = keyStrs[i];
        }
        try
        {

            var values = CacheRedis.StringGet(keys);
            for (var i = 0; i < values.Length; i++)
            {
                addrs[i] = values[i];
            }
            return addrs;
        }
        catch (Exception ex)
        {
            //Log.LogError("RedisHelper->StringGetMany 出错\r\n" + ex.ToString());
            return null;
        }
    }
    /// 
    /// 获取一个key的对象
    /// 
    /// 
    /// 
    /// 
    public T GetStringKey(string key)
    {
        return JsonConvert.DeserializeObject(CacheRedis.StringGet(key));
    }

    #endregion

    #region --删除设置过期--
    /// 
    /// 删除单个key
    /// 
    /// redis key
    /// 是否删除成功
    public bool KeyDelete(string key)
    {
        return CacheRedis.KeyDelete(key);
    }
    /// 
    /// 删除多个key
    /// 
    /// rediskey
    /// 成功删除的个数
    public long KeyDelete(RedisKey[] keys)
    {
        return CacheRedis.KeyDelete(keys);
    }
    /// 
    /// 判断key是否存储
    /// 
    /// redis key
    /// 
    public bool KeyExists(string key)
    {
        return CacheRedis.KeyExists(key);
    }
    /// 
    /// 重新命名key
    /// 
    /// 就的redis key
    /// 新的redis key
    /// 
    public bool KeyRename(string key, string newKey)
    {
        return CacheRedis.KeyRename(key, newKey);
    }
    /// 
    /// 删除hasekey
    /// 
    /// 
    /// 
    /// 
    public bool HaseDelete(RedisKey key, RedisValue hashField)
    {
        return CacheRedis.HashDelete(key, hashField);
    }
    /// 
    /// 移除hash中的某值
    /// 
    /// 
    /// 
    /// 
    /// 
    public bool HashRemove(string key, string dataKey)
    {
        return CacheRedis.HashDelete(key, dataKey);
    }
    /// 
    /// 设置缓存过期
    /// 
    /// 
    /// 
    public void SetExpire(string key, DateTime datetime)
    {
        CacheRedis.KeyExpire(key, datetime);
    }
    #endregion

}

}
③封装读取配置文件的类
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
public class AppConfigurtaionServices
{
public static IConfiguration Configuration { get; set; }
static AppConfigurtaionServices()
{
//ReloadOnChange = true 当appsettings.json被修改时重新加载
Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = “appsettings.json”, ReloadOnChange = true })
.Build();
}}

.net core3.1 Redis使用_第1张图片
④appsetting.json配置
//redis分布式缓存
“RedisConfig”: {
//是否打开缓存1是0否
“IsOpenCache”: “0”,
“ReadWriteHosts”: “127.0.0.1:6379,password=123456”,
“ReadOnlyHosts”: “127.0.0.1:6379,password=123456”
}
⑤测试调用
public IActionResult Index()
{
#region --测试redis–
var a=RedisHelperNetCore.Default.StringSet(“redis”, “redis” + DateTime.Now, TimeSpan.FromSeconds(1000000));
var b = RedisHelperNetCore.Default.StringGet(“redis”);
//var c= RedisHelper.Default.KeyDelete(“redis”);
#endregion
return View();
}

你可能感兴趣的:(.net,core3.1,redis,c#)