Отношения между StackExchange.Redis и SQL Server - PullRequest
0 голосов
/ 10 ноября 2019

Недавно я решил использовать Redis для кэширования памяти, потому что это быстрее, и не стоит создавать дополнительные таблицы только из-за одной моей конкретной стратегии.

У меня есть два класса, которые имеют отношения междудруг с другом и BotSession, соответственно, связаны с другим классом из MSSQL.

Эти отношения жизненно важны. Это возможно? Если нет, что бы вы мне порекомендовали? Я решил использовать кеш, потому что он загружается быстрее.

Мне нужно хранить временные объекты класса в кеше памяти.

builder.Entity<BotSession>(entity =>
{
    entity.HasOne(bs => bs.Bot)
        .WithMany(b => b.BotSessions)
        .HasForeignKey(bs => bs.BotId)
        .OnDelete(DeleteBehavior.Cascade);

    // Unique key
    entity.HasIndex(bs => new { bs.TrendType, bs.BotId })
        .IsUnique();
});

builder.Entity<Aggregation>(entity =>
{
    entity.HasOne(a => a.BotSession)
        .WithMany(bs => bs.Aggregations)
        .HasForeignKey(a => a.BotSessionId)
        .OnDelete(DeleteBehavior.Cascade);

    // Unique key
    entity.HasIndex(a => new { a.Type, a.BotSessionId })
        .IsUnique();
});
public class Aggregation
{
    public Aggregation()
    {
    }

    public Aggregation(AggregationType type, BinanceKline kline, int botSessionId)
    {
        Type = type;
        OpenTime = kline.OpenTime;
        CloseTime = kline.CloseTime;
        Open = kline.Open;
        High = kline.High;
        Low = kline.Low;
        Close = kline.Close;
        Volume = kline.Volume;
        BotSessionId = botSessionId;
    }

    public int Id { get; set; }
    public DateTime OpenTime { get; set; }
    public DateTime CloseTime { get; set; }

    [Column(TypeName = "decimal(18,8)")]
    public decimal Open { get; set; }

    [Column(TypeName = "decimal(18,8)")]
    public decimal High { get; set; }

    [Column(TypeName = "decimal(18,8)")]
    public decimal Low { get; set; }

    [Column(TypeName = "decimal(18,8)")]
    public decimal Close { get; set; }

    [Column(TypeName = "decimal(18,8)")]
    public decimal Volume { get; set; }

    public AggregationType Type { get; set; }

    public int BotSessionId { get; set; }
    public BotSession BotSession { get; set; }
}

public class BotSession
{
    public BotSession()
    {
    }

    public BotSession(TrendType trendType, int botId)
    {
        TrendType = trendType;
        CanTrade = false;
        StopLossValue = null;
        BotId = botId;
    }

    public int Id { get; set; }
    public TrendType TrendType { get; set; }
    public bool CanTrade { get; set; }

    [Column(TypeName = "decimal(18,8)")]
    public decimal? StopLossValue { get; set; }

    [Column(TypeName = "decimal(18,8)")]
    public decimal? NTimes { get; set; }

    public int BotId { get; set; }
    public Bot Bot { get; set; }

    public List<Aggregation> Aggregations { get; set; }

    public bool IsUptrendSession()
        => TrendType == TrendType.Uptrend;
}
public static class CacheExtensions
{
    public static async Task<T> SetAsync<T>(this IDistributedCache cache, string key, T item)
    {
        var json = JsonConvert.SerializeObject(item);

        await cache.SetStringAsync(key, json);

        return await cache.GetAsync<T>(key);
    }

    public static async Task<T> SetAsync<T>(this IDistributedCache cache, string key, T item, int expirationInHours)
    {
        var json = JsonConvert.SerializeObject(item);

        await cache.SetStringAsync(key, json, new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(expirationInHours)
        });

        return await cache.GetAsync<T>(key);
    }

    public static async Task<T> GetAsync<T>(this IDistributedCache cache, string key)
    {
        var json = await cache.GetStringAsync(key);

        if (json == null)
            return default;

        return JsonConvert.DeserializeObject<T>(json);
    }
}

// usage
var asd = await _cache.GetAsync<List<BotSession>>("Hey");
await _cache.SetAsync("Hey", sessions);
await _cache.RemoveAsync("Hey");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...