• 关于 .net core Redis 的基本用法(string /hash/list/set/sort set)


    //首先自己安装好Redis并且完成配置

    一、 配置步骤

    1、解压到适当位置 2、配置环境变量(非必须) 3、配置成windows服务启动 4、redis-cli命令检测是否安装成功

    二、.net core 引用NuGet程序包

     StackExchange.Redis

    三、 拖入帮助类

    using Microsoft.Extensions.Configuration;
    using StackExchange.Redis;
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;

    namespace Demo.CoreRedis.Simple
    {

    /*
    * 引用NuGet包 StackExchange.Redis
    *
    * 思路:
    * 1、通边注入RedisClientSingleon单例对象获取RedisClientHelper实例对象
    * (这一步也可以省略,直接注入clienthelper)
    *
    * 2、在ClientHelper中获取Redis服务器的配置连接
    * 2.1、
    *
    * **/


    public class RedisClientHelper : IDisposable
    {

    IConfiguration Configuration;
    string ConnectionStr;
    string InstanceName;
    int DefaultDB;
    ConcurrentDictionary<string, ConnectionMultiplexer> _connections;

    /// <summary>
    ///
    /// </summary>
    /// <param name="_Configuration"></param>
    /// <param name="_ConnectionKey">节点</param>
    /// <param name="_ConnectionName">连接字符串名称</param>
    /// <param name="_InstanceName">实例名称</param>
    /// <param name="_defaultDB">默认数据库</param>
    public RedisClientHelper(IConfiguration _Configuration, string _ConnectionKey, string _ConnectionName,string _InstanceName,int _DefaultDB = 0)
    {
    _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
    Configuration = _Configuration;
    var section = Configuration.GetSection(_ConnectionKey);
    ConnectionStr = section.GetSection(_ConnectionName).Value;
    InstanceName = section.GetSection(_InstanceName).Value;
    DefaultDB = _DefaultDB;
    }


    /// <summary>
    /// 获取ConnectionMultiplexer
    /// </summary>
    /// <returns></returns>
    private ConnectionMultiplexer GetConnect()
    {
    return _connections.GetOrAdd(InstanceName, p => ConnectionMultiplexer.Connect(ConnectionStr));
    }

    /// <summary>
    /// 获取数据库
    /// </summary>
    /// <param name="configName"></param>
    /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
    /// <returns></returns>
    public IDatabase GetDatabase()
    {
    return GetConnect().GetDatabase(DefaultDB);
    }

    public void Dispose()
    {
    throw new NotImplementedException();
    }
    }

    /// <summary>
    /// 获取RedisClient的单例
    /// </summary>
    public class RedisClientSingleon
    {
    static RedisClientHelper _client;
    static object _lock = new object();

    public static RedisClientHelper GetRedisInstance(IConfiguration Configuration, string _ConnectionKey, string _ConnectionName, string _InstanceName, int _DefaultDB=0)
    {
    if (_client == null)
    {
    lock (_lock)
    {
    if (_client == null)
    {
    _client = new RedisClientHelper(Configuration, _ConnectionKey, _ConnectionName, _InstanceName, _DefaultDB);
    }
    }
    }

    return _client;
    }
    }
    }

    四、用redis 五种方式进行对数据的读和写

    //RedisClientHelper redisClient;
    IDatabase _redis;
    public ReidsController(RedisClientHelper client)
    {
    //redisClient = client;
    _redis = client.GetDatabase();
    }
    //String
    [Route("StringRedis")]
    [HttpGet]
    public IActionResult GetString(string key)
    {
    string result = "";
    if (_redis.KeyExists(key))
    {
    result = _redis.StringGet(key);
    }
    else
    {
    _redis.StringSet(key,"我是String类型"+DateTime.Now);
    result = "Redis没有该值";
    }
    return Ok(new { key = key, result = result });
    }
    //List(字符串)
    [Route("ListRedis")]
    [HttpGet]
    public IActionResult GetList(string key)
    {
    string result = "";
    if (_redis.KeyExists(key))
    {
    result = _redis.ListLeftPop(key);
    }
    else
    {
    _redis.ListLeftPush(key, "List入栈" + DateTime.Now);

    }
    return Ok(new { key = key, result = result });
    }
    //List(字典)
    [Route("GetListDictory")]
    [HttpGet]
    public IActionResult GetListDictory(string key)
    {
    List<string> list = new List<string>() { "Value1", "Value2", "Value3" };
    RedisValue value = new RedisValue();
    if (_redis.KeyExists(key))
    {
    //出栈
    value = _redis.ListLeftPop(key);
    }
    else
    {
    //入栈
    _redis.ListLeftPush(key, System.Text.Json.JsonSerializer.Serialize(list) + DateTime.Now);
    }
    return Ok(new { key=key,value=value});
    }
    //Hash
    [Route("GetHash")]
    [HttpGet]
    public IActionResult GetHash(string key,string name)
    {
    string result = "";
    if (_redis.HashExists(key,name))
    {
    result = _redis.HashGet(key,name);
    }
    else
    {
    _redis.HashSet(key, name, "我是Hash1呀,我的哥哥");

    }
    return Ok(new { key = key, name = name, result = result });
    }
    //集合
    [Route("GetSet")]
    [HttpGet]
    public IActionResult GetSet(string key)
    {
    string result = "";
    if (_redis.KeyExists(key))
    {
    //读取值
    result = _redis.SetPop(key);
    }
    else
    {
    _redis.SetAdd(key, "我是集合Set");
    }
    return Ok(new { key = key, result = result });
    }
    //有序集合
    [HttpGet]
    [Route("GetSSet")]
    public IActionResult GetSSet(string key)
    {
    RedisValue[] r = null;
    if (_redis.KeyExists(key))
    {
    r = _redis.SortedSetRangeByScore(key);
    }
    else
    {
    //生产随机数
    List<int> lt = new List<int>();
    for (int i = 0; i < 4; i++)
    {
    lt.Add(new Random().Next(10, 20));
    }
    lt.ForEach(p => {
    _redis.SortedSetAdd(key, "我是sortedset类型," + (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000, p);
    });
    }
    return Ok(new { key = key, result = r });
    }

  • 相关阅读:
    PostgreSQL 慢查询SQL语句跟踪
    unity WheelCollider调整
    C# 事件event
    C# 委托
    C4D导入fbx到Unity设置
    3DMAX导出fbx到unity设置
    unity 单面模型shader
    对数平均数
    GameObject:activeInHierarchy、activeSelf Behaviour:enabled
    unity Time.deltaTime
  • 原文地址:https://www.cnblogs.com/lishiyiya/p/14063218.html
Copyright © 2020-2023  润新知