首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Redis与Server性能

Redis与Server性能
EN

Stack Overflow用户
提问于 2020-07-13 18:21:50
回答 3查看 10.4K关注 0票数 11

应用程序性能是在关系数据库上使用缓存的主要原因之一。由于它以键值对的形式将数据存储在内存中,因此可以将经常访问的数据存储在缓存中,而这些数据并不是经常更改的。从缓存读取数据要比数据库快得多。Redis是分布式缓存市场上最好的解决方案之一。

我正在Azure Redis缓存和Azure SQL Server之间进行性能测试。我创建了一个简单的ASP.NET核心应用程序,并在其中多次从Server数据库和Redis读取数据,并比较它们之间的读取时间。对于数据库读取,我使用了实体框架核心(),对于Redis读取,我使用了'Microsoft.Extensions.Caching.StackExchangeRedis'.

模型

代码语言:javascript
运行
复制
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;
        }
    }
}

实体框架核心数据上下文。

代码语言:javascript
运行
复制
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; }
    }
}

启动类

代码语言:javascript
运行
复制
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;
    });
}

appsettings.json

代码语言:javascript
运行
复制
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
     }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "StudentDbConnectionString": "[Azure SQL Server connection string]",
    "RedisConnectionString": "[Azure Redis cache connection string]"
  }
}

家庭控制器

代码语言:javascript
运行
复制
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.cshtml视图

代码语言:javascript
运行
复制
@{
    ViewData["Title"] = "Home Page";
}

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

我发现Server比Redis更快。

ASP.NET核心应用程序托管在Azure中,与Azure和Azure的位置相同。

请告诉我为什么Redis比SQL Server慢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-07-17 06:37:53

我使用github.com/dotnet/BenchmarkDotNet对Azure数据库和Redis的Azure缓存进行基准测试,以进行10000的读取。Server数据库平均为16.48秒,Redis为29.53秒。

我使用过JMeter,并连接了100个用户,每个用户读取Server数据库/Redis 1000次。完成SQL Server数据库与Redis的读取所用的总时间没有太大差别(两者都在3分钟左右30秒左右),但我看到Azure SQL Server数据库DTU上有负载。在测试期间,DTU接近100%。

总之,我认为速度不是在Server数据库上使用Redis缓存的唯一原因,但另一个原因是Redis缓存减少了来自数据库的大量负载。

票数 12
EN

Stack Overflow用户

发布于 2022-02-22 19:45:28

你不仅在这里看到了性能的差异。对于缓存,Redis还为您提供了缓存失效逻辑,需要在内存表中的SQL中构建该逻辑。所以当涉及到缓存时,Redis一直都是

票数 0
EN

Stack Overflow用户

发布于 2022-09-15 07:19:29

想想这里发生了什么

在SQL进程中,-> TCP ->读取优化存储(单表) ->序列化为应用程序模型。

在Redis进程中,->检查缓存命中-> TCP ->读取优化存储(单表) ->序列化为应用程序模型

Redis很好,但是不要弄错它的用途,如果您是在优化的索引上读取索引表,那么SQL会很快,为什么Redis会更快呢?当您的授权存储或进程必须做一些计算才能获得结果时,分布式缓存的功能就来了,因此通过缓存有效地节省CPU磁盘/时间(无论是在sql上还是在proc中)。

如果您想真正提高速度--您想要的是内存缓存中的速度--然而,这并不像最初听起来那么简单,这里真正的诀窍是,在对授权存储进行更改时,可以通过分布式集群在内存缓存中失效。

希望这能有所帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62881953

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档