Redis 实现分布式缓存

Redis 实现分布式缓存

IDistributedCache、StackExchangeRedis

Redis 学习教程:

Windows安装redis并将redis设置成服务开机自启:
https://blog.csdn.net/qq_40732336/article/details/122653953

Redis 中文网 https://www.redis.net.cn/

搭建 Master/Slaver 模式的 Redis 集群 https://blog.csdn.net/lupengfei1009/article/details/88323561#_154

使用 Redis Desktop Manager 连接 Redis

1565870987(1)

二,ASP.NET Core 使用分布式缓存

ASP.NET Core 中,支持使用多种数据库进行缓存,ASP.NET Core 提供了统一的接口给开发者使用。

IDistributedCache

ASP.NET Core 中,使用 IDistributedCache 为开发者提供统一的缓存使用接口,而不必关注使用的是何种数据库。

IDistributedCache]接口提供了以下方法操作的分布式的缓存实现中的项:

  • GetAsync –接受字符串键和检索缓存的项作为byte[]数组如果在缓存中找到。
  • SetAsync –中添加项 (作为byte[]数组) 到使用字符串键的缓存。
  • RefreshAsync –刷新缓存基于其密钥,重置其滑动到期超时值 (如果有) 中的项。
  • RemoveAsync –移除缓存项根据其字符串键值。

IDistributedCache 提供的常用方法如下:

方法说明
Get(String)获取Key(键)的值
GetAsync(String, CancellationToken)异步获取键的值
Refresh(String)刷新缓存
RefreshAsync(String, CancellationToken)Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any).
Remove(String)移除某个值
RemoveAsync(String, CancellationToken)Removes the value with the given key.
[Set(String, Byte], DistributedCacheEntryOptions)Sets a value with the given key.
[SetAsync(String, Byte], DistributedCacheEntryOptions, CancellationToken)Sets the value with the given key.

官方文档很详细https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache?view=aspnetcore-2.2

ASP.NET Core 中配置缓存

新建一个 ASP.NET Core WebApi 项目

Nuget 管理器安装

Microsoft.Extensions.Caching.StackExchangeRedis

ConfigureServices 中使用服务

services.AddDistributedMemoryCache();

配置 Redis 服务器

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = "localhost:6379";
                options.InstanceName = "mvc";
            });

InstanceName 是你自定义的实例名称,创建缓存时会以此名称开头。

这样就配置好了。

使用缓存

修改默认生成的 ValuesController.cs。

注入缓存服务

        private readonly IDistributedCache _cache;
        public ValuesController(IDistributedCache cache)
        {
            _cache = cache;
        }

设置缓存和使用缓存:

await _cache.GetAsync("{键名}");
_cache.SetAsync("键名", {}, {设置});

删除原来的方法,添加以下代码:

        [HttpGet("Set")]
        public async Task<JsonResult> SetCache(string setkey, string setvalue)
        {

            string key = "key1";
            if (!string.IsNullOrEmpty(setkey))
                key = setkey;
            string value = DateTime.Now.ToLongTimeString();
            if (!string.IsNullOrEmpty(setvalue))
                value = setvalue;
            await _cache.SetStringAsync(key, value);
            return new JsonResult(new { Code = 200, Message = "设置缓存成功", Data = "key=" + key + "    value=" + value });
        }

        [HttpGet("Get")]
        public async Task<JsonResult> GetCache(string setkey)
        {
            string key = "key1";
            if (!string.IsNullOrEmpty(setkey))
                key = setkey;
            var value = await _cache.GetStringAsync(key);
            return new JsonResult(new { Code = 200, Message = "设置缓存成功", Data = "key=" + key + "    value=" + value });
        }

在 URL 添加 QueryString 可以设置缓存内容,如果没有带参数的话,就使用默认的值。

打开 https://localhost:5001/api/values/set 可以看到设置了默认值。

或者访问 https://localhost:5001/api/values/set?setkey=key11111&setvalue=asafesfdsreg

自定义设置缓存值。

1565872816(1)

打开 https://localhost:5001/api/values/get?setkey=key11111

可以获取缓存值。

设置缓存过期时间

使用 DistributedCacheEntryOptions 可以设置缓存过期时间

DistributedCacheEntryOptions 有三个属性,表示相对时间、绝对时间。

使用方法

        [HttpGet("Set")]
        public async Task<JsonResult> SetCache(string setkey, string setvalue)
        {

            string key = "key1";
            if (!string.IsNullOrEmpty(setkey))
                key = setkey;
            string value = DateTime.Now.ToLongTimeString();
            if (!string.IsNullOrEmpty(setvalue))
                value = setvalue;

            var options = new DistributedCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromSeconds(20));

            await _cache.SetStringAsync(key, value, options);
            return new JsonResult(new { Code = 200, Message = "设置缓存成功", Data = "key=" + key + "    value=" + value });
        }

缓存 20 秒,20秒过后此缓存将被清除。

参考:https://www.cnblogs.com/whuanle/p/11360468.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值