­

ServiceStack.Redis 的 ASP.NET Core 擴展庫

給大家安利一款 ServiceStack.Redis 的 ASP.NET Core 擴展庫,它是基於 ServiceStack.Redis.Core 開發的。 簡單易用,開源免費,使用ASP.NET Core自身提供的DI容器來實現針對服務的註冊和消費。直接在程序啟動時註冊到服務中即可完成全部配置,對於小白用戶也可快速上手Redis緩存和Redis分佈式緩存。

Install Package

//www.nuget.org/packages/ServiceStack.Redis.Extension.AspNetCore

Configure

Startup.cs

Single Server

public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedServiceStackRedisCache(options =>
    {
        // default single server: 127.0.0.1:6379
        // services.AddServiceStackRedisCache();
        
        // customize single server
        services.AddServiceStackRedisCache(options =>{
        	options.SingleServer = "123456@127.0.0.1:6379";
        });
    }
                                                  
    services.AddControllers();
}

Read and write separation

public void ConfigureServices(IServiceCollection services)
{
    services.AddServiceStackRedisCache(options =>
    {
        options.ReadWriteServers = new[]
        {
            "192.168.1.1:6379", "123456@192.168.1.2:6379", "123456@192.168.1.3:6379", "123456@192.168.1.4:6379"
        };
        options.ReadOnlyServers = new[]
        {
            "192.168.1.1:6379", "123456@192.168.1.3:6379"
        };
    });

    services.AddControllers();
}

Load from configuration

public void ConfigureServices(IServiceCollection services)
{
   
services.AddServiceStackRedisCache(Configuration.GetSection("ServiceStackRedisOptions"));

    services.AddControllers();
}

appsettings.Development.json

{
  "ServiceStackRedisOptions": {
    "SingleServer": "1234546@127.0.0.1:6379"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

appsetting.json

{
  "ServiceStackRedisOptions": {
    "ReadWriteServers": ["192.168.1.1:6379", "123456@192.168.1.2:6379", "123456@192.168.1.3:6379", "123456@192.168.1.4:6379"],
    "ReadOnlyServers": ["192.168.1.1:6379", "123456@192.168.1.3:6379"] 
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

ServiceStack.Redis Options

public class ServiceStackRedisOptions
{
    /// <summary>
    ///     單機的地址,例如:127.0.0.1:6379(默認值)。如果你只用到一個Redis服務端,那麼配置此項即可。
    /// </summary>
    public string SingleServer { get; set; } = "127.0.0.1:6379";

    /// <summary>
    ///     讀寫的地址,例如:{ "192.168.1.1:6379","123456@192.168.1.2:6379","123456@192.168.1.3:6379","123456@192.168.1.4:6379" }
    /// </summary>
    public string[] ReadWriteServers { get; set; }

    /// <summary>
    ///     只讀地址,例如:{ "192.168.1.1:6379","123456@192.168.1.3:6379" }
    /// </summary>
    public string[] ReadOnlyServers { get; set; }

    /// <summary>
    ///     MaxWritePoolSize寫的頻率比讀低。默認值 8
    /// </summary>
    public int MaxWritePoolSize { get; set; } = 8;

    /// <summary>
    ///     MaxReadPoolSize讀的頻繁比較多。默認值 12,Redis官方聲明最大連接數為1W,但是連接數要控制。
    /// </summary>
    public int MaxReadPoolSize { get; set; } = 12;

    /// <summary>
    ///     連接最大的空閑時間。默認值 60,Redis官方默認是240
    /// </summary>
    public int IdleTimeOutSecs { get; set; } = 60;

    /// <summary>
    ///     連接超時時間,毫秒。默認值 6000
    /// </summary>
    public int ConnectTimeout { get; set; } = 6000;

    /// <summary>
    ///     數據發送超時時間,毫秒。默認值 6000
    /// </summary>
    public int SendTimeout { get; set; } = 6000;

    /// <summary>
    ///     數據接收超時時間,毫秒。默認值 6000
    /// </summary>
    public int ReceiveTimeout { get; set; } = 6000;

    /// <summary>
    ///     連接池取鏈接的超時時間,毫秒。默認值 6000
    /// </summary>
    public int PoolTimeout { get; set; } = 6000;

    /// <summary>
    ///     默認的數據庫。默認值 0,Redis官方默認也是0
    /// </summary>
    public long DefaultDb { get; set; } = 0;
}

Usage

WeatherForecastController.cs

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IServiceStackRedisCache _redisCache;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IServiceStackRedisCache redisCache)
    {
        _logger = logger;
        this._redisCache = redisCache;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var array = _redisCache.Get<WeatherForecast[]>("WeatherForecast");
        if (array == null)
        {
            var rng = new Random();
            array = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            }).ToArray();

            // Cache for 30 minutes
            _redisCache.Set("WeatherForecast", array, 60 * 1 * 30);
        }

        return array;
    }
}
Tags: