首页 > 数据库 >01.net6集成redis

01.net6集成redis

时间:2023-07-06 18:15:28浏览次数:61  
标签:Task return string redis 01 dict key var net6

安装redis

自己使用docker compose安装redis,yml文件如下:

version: '3.9'
services:
  redis:
    image: redis:6.2.5
    container_name: docker_redis
    privileged: true
    volumes:
      - ./data:/data
      - ./conf/redis.conf:/usr/local/etc/redis/redis.conf
      - ./logs:/logs
    command: ["redis-server","/usr/local/etc/redis/redis.conf"]
    ports:
      - 6379:6379
    environment:
      - TZ="Asia/Shanghai"

.net6添加redis

1.安装nuget包:StackExchange.Redis

2.appsetting.json添加redis配置:

"Redis": {
  "host": "192.168.33.10",
  "port": 6379,
  "password": "12345",
  "maxWritePoolSize": 60,
  "maxReadPoolSize": 60,
  "autoStart": true,
  "localCacheTime": 36000,
  "recordeLog": false,
  "preName": ""
} 

3.添加接口和实现类

IRedisCache.cs:

using StackExchange.Redis;

namespace Hui.Core.Extensions.Resis;

public interface IRedisCache
{
    /// <summary>
    /// 设置缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="expireTime"></param>
    /// <returns></returns>
    Task<bool> SetCache<T>(string key, T value, DateTime? expireTime = null);

    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    Task<T> GetCache<T>(string key);

    /// <summary>
    /// 根据键精准删除
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    Task<bool> RemoveCache(string key);

    /// <summary>
    /// 模糊删除,左侧匹配,右模糊
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    Task RemoveKeysLeftLike(string key);

    /// <summary>
    /// 获取自增id
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    Task<long> GetIncr(string key);

    /// <summary>
    /// 获取自增id
    /// </summary>
    /// <param name="key"></param>
    /// <param name="expTimeSpan"></param>
    /// <returns></returns>
    Task<long> GetIncr(string key, TimeSpan expTimeSpan);

    #region Hash
    Task<int> SetHashFieldCache<T>(string key, string fieldKey, T fieldValue);
    Task<int> SetHashFieldCache<T>(string key, Dictionary<string, T> dict);
    Task<T> GetHashFieldCache<T>(string key, string fieldKey);
    Task<Dictionary<string, T>> GetHashFieldCache<T>(string key, Dictionary<string, T> dict);
    Task<Dictionary<string, T>> GetHashCache<T>(string key);
    Task<List<T>> GetHashToListCache<T>(string key);
    Task<bool> RemoveHashFieldCache(string key, string fieldKey);
    Task<Dictionary<string, bool>> RemoveHashFieldCache(string key, Dictionary<string, bool> dict);
    #endregion


    #region 列表(List) 操作

    Task<long> ListLeftPushAsync(string redisKey, string redisValue);
    Task<long> ListRightPushAsync(string redisKey, string redisValue);

    #endregion


    #region 有序集合(Sorted Set)

    Task<bool> SortedSetAddAsync(string redisKey, string redisValue, DateTime time);

    #endregion

    ISubscriber GetSubscriber();
}

RedisCache.cs:

using Hui.Core.Common.Helper;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using StackExchange.Redis;

namespace Hui.Core.Extensions.Resis;

public class RedisCache:IRedisCache
{
    private readonly IDatabase _database;
    private readonly ConnectionMultiplexer _connectionMultiplexer;

    public RedisCache()
    {
        //把appsetting.json中配置的Redis连接配置注入进来,连接Redis
        var redisHost = AppSettingsHelper.ReadAppSettings("Redis", "host");  
        var redisPort = AppSettingsHelper.ReadAppSettings("Redis", "port").ObjToInt();

        var configurationOptions = new ConfigurationOptions
        {
            EndPoints =
            {
                { redisHost, redisPort }
            },
            KeepAlive = 180,
            //Password =  AppSettingsHelper.ReadAppSettings("Redis", "password");
            AllowAdmin = true
        };
        _connectionMultiplexer = ConnectionMultiplexer.Connect(configurationOptions);
        _database = _connectionMultiplexer.GetDatabase();
        
    }




    public async Task<bool> SetCache<T>(string key, T value, DateTime? expireTime = null)
    {
        try
        {
            var jsonOption = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            var strValue = JsonConvert.SerializeObject(value, jsonOption);
            if (string.IsNullOrEmpty(strValue))
                return false;
            if (expireTime == null)
                return await _database.StringSetAsync(InitKey(key), strValue);

            return await _database.StringSetAsync(InitKey(key), strValue, expireTime.Value - DateTime.Now);
        }
        catch(Exception ex) { }

        return false;
    }
    
    public async Task<T> GetCache<T>(string key)
    {
        var t = default(T);
        try
        {
            var value = await _database.StringGetAsync(InitKey(key));
            if (string.IsNullOrEmpty(value)) return t;
            t = JsonConvert.DeserializeObject<T>(value);
        }
        catch (Exception ex)
        {
            // ignored
        }

        return t;
    }

    public async Task<bool> RemoveCache(string key)
    {
        return await _database.KeyDeleteAsync(InitKey(key));
    }

    public async Task RemoveKeysLeftLike(string key)
    {
        var redisResult = await _database.ScriptEvaluateAsync(LuaScript.Prepare(
            //Redis的keys模糊查询:
            " local res = redis.call('KEYS', @keywords) " +
            " return res "), new { @keywords = $"{InitKey(key)}*" });
        if (!redisResult.IsNull)
            await _database.KeyDeleteAsync((RedisKey[])redisResult); //删除一组key
    }

    public async Task<long> GetIncr(string key)
    {
        try
        {
            return await _database.StringIncrementAsync(InitKey(key));
        }
        catch (Exception e)
        {
            return 0;
        }
    }

    public async Task<long> GetIncr(string key, TimeSpan expTimeSpan)
    {
        try
        {
            var qty = await _database.StringIncrementAsync(InitKey(key));
            if (qty == 1)
            {
                //设置过期时间
                await _database.KeyExpireAsync(key, expTimeSpan);
            }

            return qty;
        }
        catch (Exception e)
        {
            return 0;
        }
    }

    public async Task<int> SetHashFieldCache<T>(string key, string fieldKey, T fieldValue)
    {
        return await SetHashFieldCache<T>(InitKey(key), new Dictionary<string, T> { { fieldKey, fieldValue } });
    }

    public async Task<int> SetHashFieldCache<T>(string key, Dictionary<string, T> dict)
    {
        var count = 0;
        var jsonOption = new JsonSerializerSettings()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };
        foreach (var fieldKey in dict.Keys)
        {
            var fieldValue = JsonConvert.SerializeObject(dict[fieldKey], jsonOption);
            count += await _database.HashSetAsync(InitKey(key), fieldKey, fieldValue) ? 1 : 0;
        }
        return count;
    }

    public async Task<T> GetHashFieldCache<T>(string key, string fieldKey)
    {
        var dict = await GetHashFieldCache<T>(InitKey(key), new Dictionary<string, T> { { fieldKey, default(T) } });
        return dict[fieldKey];
    }

    public async Task<Dictionary<string, T>> GetHashFieldCache<T>(string key, Dictionary<string, T> dict)
    {
        foreach (string fieldKey in dict.Keys)
        {
            string fieldValue = await _database.HashGetAsync(InitKey(key), fieldKey);
            dict[fieldKey] = JsonConvert.DeserializeObject<T>(fieldValue);
        }
        return dict;
    }

    public async Task<Dictionary<string, T>> GetHashCache<T>(string key)
    {
        var dict = new Dictionary<string, T>();
        var hashFields = await _database.HashGetAllAsync(InitKey(key));
        foreach (var field in hashFields)
        {
            dict[field.Name] = JsonConvert.DeserializeObject<T>(field.Value);
        }
        return dict;
    }

    public async Task<List<T>> GetHashToListCache<T>(string key)
    {
        var list = new List<T>();
        var hashFields = await _database.HashGetAllAsync(InitKey(key));
        foreach (var field in hashFields)
        {
            list.Add(JsonConvert.DeserializeObject<T>(field.Value));
        }
        return list;
    }

    public async Task<bool> RemoveHashFieldCache(string key, string fieldKey)
    {
        var dict = new Dictionary<string, bool> { { fieldKey, false } };
        dict = await RemoveHashFieldCache(InitKey(key), dict);
        return dict[fieldKey];
    }

    public async Task<Dictionary<string, bool>> RemoveHashFieldCache(string key, Dictionary<string, bool> dict)
    {
        foreach (var fieldKey in dict.Keys)
        {
            dict[fieldKey] = await _database.HashDeleteAsync(InitKey(key), fieldKey);
        }
        return dict;
    }



    #region list

    public async Task<long> ListLeftPushAsync(string redisKey, string redisValue)
    {
        return await _database.ListLeftPushAsync(redisKey, redisValue);
    }

    public async Task<long> ListRightPushAsync(string redisKey, string redisValue)
    {
        return await _database.ListRightPushAsync(redisKey, redisValue);
    }

    #endregion

    #region 有序集合(Sorted Set)

    public async Task<bool> SortedSetAddAsync(string redisKey, string redisValue, DateTime time)
    {
        var sort = DateHelper.ToUnixTimestampBySeconds(time);
        return await _database.SortedSetAddAsync(redisKey, redisValue, sort);
    }

    #endregion


    private string InitKey(string key)
    {
        //return $"{_webApplicationBuilder.Configuration["Redis:preName"]}{key}";
        return $"{AppSettingsHelper.ReadAppSettings("Redis", "preName")}{key}";
    }


    public ISubscriber GetSubscriber()
    {
        return _connectionMultiplexer.GetSubscriber();
    }

}

Program.cs中,注入redis

//注入Redis
builder.Services.AddSingleton<IRedisCache, RedisCache>();

通过构造函数注入来使用

await _redisCache.SetCache<string>("haha_key", "haha_value");

结果如下:

RedisDesktopManager

参考:

标签:Task,return,string,redis,01,dict,key,var,net6
From: https://www.cnblogs.com/huiteresa/p/17532933.html

相关文章

  • 错误:rpmdb: BDB0113 Thread/process 8709/139671674841152 failed
    rpm库报错错误:rpmdb:BDB0113Thread/process8709/139671674841152failed:BDB1507ThreaddiedinBerkeleyDBlibrary错误:db5错误(-30973)来自dbenv->failchk:BDB0087DB_RUNRECOVERY:Fatalerror,rundatabaserecovery错误:无法使用db5- (-30973)打开Packages......
  • 云拨测全面升级丨单次拨测低至 0.001 元
    作者:少焉随着云原生、微服务技术的发展,可观测需求变得越来越强烈,作为可观测技术的重要能力之一,云拨测(SyntheticsMonitor)由于其零侵入、开箱即用、主动式监测手段,也受到很多用户的青睐,很多通过云拨测主动监测自身服务的可用性,先于用户发现线上异常;也会通过云拨测分析和优化网页加......
  • gym101573I Favorite Points
    gym101573IFavoritePoints纪念一下。#include<bits/stdc++.h>#defineLLlonglong#definePLLpair<LL,LL>#defineMPmake_pair#defineEBemplace_back#defineall(x)x.begin(),x.end()usingnamespacestd;template<typenameT>voidchkmn(T......
  • JAVA_DAY_01
    第一天1.jdk针对Java开发员的软件开发工具包。1.5:{自动拆箱和装箱、foreach循环、可变参数}​1.8:{1、Lamdba表达式2、函数式接口3、方法引用和构造引用4、StreamAPI}​java的运行机制,编写定义为.java格式的源代码。​通过javac命令格式调用编译器(JDK)对源代码进行编......
  • 【Redis】- 常用命令
    Redis的启动方式./redis-server&redis-serverredis.windows.confRedis的启动脚本启动脚本redis_init_script位于位于Redis的/utils/目录下,redis_init_script脚本代码如下:#!/bin/sh##SimpleRedisinit.dscriptconceivedtoworkonLinuxsystems#asitdoes......
  • 龙芯电脑编译redis (loongarch)
    1、获取源码源码地址:https://redis.io/download/#redis-downloads 最新版本是7.2,这里用redis5测试,最后一个版本是5.0.14wgethttps://download.redis.io/releases/redis-5.0.14.tar.gztar-zxvfredis-5.0.14.tar.gzcdredis-5.0.14/2、修改源码redis用到了jemalloc库......
  • docker 部署redis 主从
    创建数据目录cd/mnt&&mkdirredis-cluster&&cdredis-cluster&&mkdir-p6380/conf6381/conf6382/conf创建配置文件[root@localhostredis-cluster]#vim6380/conf/redis.conf[root@localhostredis-cluster]#vim6381/conf/redis.conf[root@l......
  • GDAL源码剖析与开发指南 - 李民录 - 2014
    本书适合地理信息系统和遥感等相关专业应用的开发人员阅读参考。本书中大部分的示例代码都是使用C/C++语言编写,有一定C/C++语言基础的读者能够快速上手开发相关应用。目录第1章GDAL简介.................1第2章OGR空间参考.............42第3章OGR库说明........................
  • 深入解析Redis的LRU与LFU算法实现
    作者:vivo互联网服务器团队-LuoJianxin重点介绍了Redis的LRU与LFU算法实现,并分析总结了两种算法的实现效果以及存在的问题。一、前言Redis是一款基于内存的高性能NoSQL数据库,数据都缓存在内存里,这使得Redis可以每秒轻松地处理数万的读写请求。相对于磁盘的容量,内存的空......
  • 01_Avalonia+.NET 6 初识篇
    https://zhuanlan.zhihu.com/p/539490994 前言应信创(主要是国产麒麟系统)的要求,最近在看C/S架构跨平台的解决方案。由于之前的系统是使用WPF开发的,使用Avalonia跨平台改动的工作量会比较小。Avalonia是一个跨平台的.NETUI框架,支持Windows,Linux,MacOSX,IOS环境......