.Core使用CSRedis


一、為什么選擇CSRedis

ServiceStack.Redis 是商業版,免費版有限制;

StackExchange.Redis 是免費版,但是內核在 .NETCore 運行有問題經常 Timeout,暫無法解決;

CSRedis於2016年開始支持.NETCore一直迭代至今,實現了低門檻、高性能,和分區高級玩法的.NETCore redis-cli SDK;

在v3.0版本更新中,CSRedis中的所有方法名稱進行了調整,使其和redis-cli保持一致,如果你熟悉redis-cli的命令的話,CSRedis可以直接上手,這樣學習成本就降低很多。

二、使用CSRedis

  安裝CSRedis

 

 

 在appsettings.json做Redis配置

{
  "Cache": {
    "CacheType": "Redis", //CacheType
    "RedisEndpoint": "127.0.0.1:6379,password=123", //Redis節點地址,定義詳見 https://github.com/2881099/csredis
    //如果Redis沒有設置密碼
    //"RedisEndpoint": "127.0.0.1:6379" //Redis節點地址,定義詳見 https://github.com/2881099/csredis
  },
  "AllowedHosts": "*"
}

自定義IHostBuilder擴展方法,注入CSRedis服務

using CSRedis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

namespace CSRedisTest
{
    public static class Extention
    {
        /// <summary>
        /// 使用緩存
        /// </summary>
        /// <param name="hostBuilder">建造者</param>
        /// <returns></returns>
        public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
        {
            hostBuilder.ConfigureServices((buidlerContext, services) =>
            {
                var cacheOption = buidlerContext.Configuration.GetSection("Cache").Get<CacheOption>();
                switch (cacheOption.CacheType)
                {
                    case CacheType.Memory: services.AddDistributedMemoryCache(); break;
                    case CacheType.Redis:
                        {
                            var csredis = new CSRedisClient(cacheOption.RedisEndpoint);
                            RedisHelper.Initialization(csredis);
                            services.AddSingleton(csredis);
                            services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
                        }; break;
                    default: throw new Exception("緩存類型無效");
                }
            });

            return hostBuilder;
        }
    }
}

在Program調用該擴展方法

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace CSRedisTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseCache()//調動方法
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

在Controller中使用CSRedis

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSRedisTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            //添加數據 字符串鍵-值對 
            RedisHelper.Set("hello", "1", 60);//設置過期時間,單位秒
            RedisHelper.Set("world", "2");//默認不過期

            // 根據鍵獲取對應的值
            string helloValue=RedisHelper.Get("hello");

            // 移除元素
            RedisHelper.Del("world");

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
            })
            .ToArray();
        }
    }
}
View Code

我們利用Redis Desktop Manager管理工具查看下數據

 

 

源碼:https://github.com/qiuxianhu/CoreComponentDemo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM