首页 > 解决方案 > 将数据存储在范围服务(按请求)中以提高性能的缺点是什么

问题描述

服务如下所示:

public class TestService
{
    private ExternalService _externalService;
    private Dictionary<int, string> _data = new Dictionary<int, string>();

    public TestService(ExternalService externalService)
    {
        _externalService = externalService;
    }

    public string GetItem(int id)
    {
        if (_data.TryGetValue(id, out var item))
        {
            return item;
        }

        var result = _externalService.GetItem(id);

        this._data.Add(id, result);

        return result;
    }
}

和注册:

services.AddScoped<TestService>();

不会从多个线程调用此服务。

这种解决方案有什么缺点?字典中可能有数百或数千个项目。mb 它会导致一些内存问题吗?

标签: c#asp.net-core

解决方案


正如你所写的那样,缺点是内存。另一个缺点是你可以获得脏值。

我会使用标准的缓存系统,比如 Redis。然后,您还可以阅读有关到期时间的信息。

带有缓存的模式本身就是数百万其他网站用来保存到不同地方的往返行程的方法。


推荐阅读