分布式缓存服务器

一、常用分布式服务器介绍

推荐用redis在高可用分布式部署比较强而Memcached比较弱而且key有限制

 个字节

redis用法

如何注入到 Controller

下面的代码清单展示了如何将 IDistributedCache 注入到 Controller 中并实现从 Redis 中进行插入和读取。

public class DefaultController : Controller
{
     private readonly IDistributedCache _distributedCache;
     
     public HomeController(IDistributedCache distributedCache)
     {
          _distributedCache = distributedCache;
     }

     [HttpGet]
     public async Task Get()
     {
          var cacheKey ="IDG";

          var data = _distributedCache.GetString(cacheKey);
          
          if (!string.IsNullOrEmpty(data))
          {
               return data; //returned from Cache
          }
          else
          {
               string str ="Hello World";
               _distributedCache.SetString(cacheKey, str);
               return str;
          }
     }
}

如何使用 SqlServer 作为缓存介质

要想将 SqlServer 作为底层的缓存介质,需要通过 Nuget 安装如下包:


Install-Package Microsoft.Extensions.Caching.SqlServer
Install-Package Microsoft.Extensions.Caching.SqlConfig.Tools
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddDistributedSqlServerCache(x =>
            {
                x.ConnectionString = Configuration["ConnectionStrings:Default"];
                x.SchemaName = "dbo";
                x.TableName = "IDGCache";
            });
        }

接下来通过如下命令在 SqlServer 中生成 Table 来存放缓存数据,代码如下:


dotnet sql-cache create 


 

扫描二维码关注公众号,回复: 15891418 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_57062986/article/details/131789700