Redis против SQL производительность сервера - PullRequest
1 голос
/ 13 июля 2020

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

Я проводил тест производительности между Azure кешем Redis и Azure SQL сервером. Я создал простое приложение ASP. NET Core, внутри которого я несколько раз прочитал данные из базы данных SQL Server, а также из Redis и сравнил время чтения между ними. Для чтения базы данных я использовал Entity Framework Core, а для чтения Redis использовал Microsoft.Extensions.Caching.StackExchangeRedis.

Model

using System;

namespace WebApplication2.Models
{
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Subject { get; set; }

        public Student()
        {
            Name = string.Empty;
            Subject = string.Empty;
        }
    }
}

Entity Framework Core data context.

using Microsoft.EntityFrameworkCore;
using WebApplication2.Models;

namespace WebApplication2.Data
{
    public class StudentContext : DbContext
    {
        public StudentContext(DbContextOptions<StudentContext> options)
            : base(options)
        {
        }

        public DbSet<Student>? Students { get; set; }
    }
}

Класс запуска

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
        
    string studentDbConnectionString = Configuration.GetConnectionString("StudentDbConnectionString");
    services.AddDbContext<StudentContext>(option => option.UseSqlServer(studentDbConnectionString));

    string redisConnectionString = Configuration.GetConnectionString("RedisConnectionString");
    services.AddStackExchangeRedisCache(options =>
    {
        options.Configuration = redisConnectionString;
    });
}

настройки приложения. json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
     }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "StudentDbConnectionString": "[Azure SQL Server connection string]",
    "RedisConnectionString": "[Azure Redis cache connection string]"
  }
}

Домашний контроллер

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using WebApplication2.Data;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class HomeController : Controller
    {
        private readonly StudentContext _studentContext;
        private readonly IDistributedCache _cache;

        public HomeController(StudentContext studentContext, IDistributedCache cache)
        {
            _studentContext = studentContext;
            _cache = cache;
        }

        public IActionResult Index()
        {
            List<Student>? students = null;
            var counter = 10000;

            var sw = Stopwatch.StartNew();
            for (var i = 0; i < counter; i++)
            {
                students = _studentContext.Students.OrderBy(student => student.Id).ToList();
            }
            sw.Stop();
            ViewData["DatabaseDuraion"] = $"Database: {sw.ElapsedMilliseconds}";

            if (students != null && students.Count > 0)
            {
                List<Student> studentsFromCache;
                var key = "Students";
                _cache.Set(key, ObjectToByteArray(students));

                sw.Restart();
                for (var i = 0; i < counter; i++)
                {
                    studentsFromCache = (List<Student>)ByteArrayToObject(_cache.Get(key));
                }
                sw.Stop();
                ViewData["RedisDuraion"] = $"Redis: {sw.ElapsedMilliseconds}";
            }

            return View();
        }

        private byte[] ObjectToByteArray(object obj)
        {
            var bf = new BinaryFormatter();
            using var ms = new MemoryStream();
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }

        private object ByteArrayToObject(byte[] arrBytes)
        {
            using var memStream = new MemoryStream();
            var binForm = new BinaryFormatter();
            memStream.Write(arrBytes, 0, arrBytes.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            object obj = binForm.Deserialize(memStream);
            return obj;
        }
    }
}

Home \ Index.cs html просмотр

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">        
    <p>@ViewData["DatabaseDuraion"]</p>
    <p>@ViewData["RedisDuraion"]</p>
</div>

Я обнаружил SQL Сервер быстрее, чем Redis.

SQL Сервер против Redis

Приложение ASP. NET Core размещается в Azure Службе приложений с тем же расположением, что и Azure SQL Server и Azure Redis.

Пожалуйста, дайте мне знать, почему Redis медленнее, чем SQL Сервер?

1 Ответ

1 голос
/ 17 июля 2020

Я использовал github.com / dotnet / BenchmarkDo tNet для тестирования Azure SQL базы данных сервера и Azure кеша для Redis на 10000 чтений. SQL Среднее значение базы данных сервера: 16,48 сеанса c и значение Redis: 29,53 сеанса c.

Я использовал JMeter и подключает 100 пользователей при каждом чтении SQL База данных сервера / Redis 1000 раз. Нет большой разницы между общим временем, которое потребовалось для завершения sh чтения SQL базы данных сервера и Redis (оба примерно 3 минуты и 30 секунд c), но я видел нагрузку на Azure SQL сервер база данных DTU. DTU приближается к 100% во время теста. база данных.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...