随笔 - 59  文章 - 20  评论 - 61  阅读 - 85494

Asp.Net Core使用redis缓存容器

Asp.Net Core使用redis缓存容器 

Asp.Net Core项目使用redis作为分布式缓存,是非常成熟的技术,微软官网有介绍:

https://learn.microsoft.com/zh-cn/aspnet/core/performance/caching/distributed?view=aspnetcore-7.0

 参考文章

https://devpress.csdn.net/redis/62f0ca82c6770329307f4654.html

《使用 Redis ASP.Net Core 中进行分布式缓存_redis_weixin_0010034-DevPress官方社区》 

 如果是小型项目,可以自行拉取一个redis容器。如果是大型项目,有钱的话可以购买云平台的redis服务,没钱的话还得自己搭建redis集群,门槛也不低。 

搭建redis容器

因为要在本机调试连接云服务器的redis容器,所以映射redis默认端口6379到外网,如果无此需求expose 6379端口即可。redis是基础设施,写一个独立的docker-compose.yml脚本启动它,在mynetwork网桥里边的其他项目可以通过容器名访问redis

 

复制代码
version: '3.7'

services:
  redis:
    container_name: redis
    image: redis:6.0-alpine
    environment:
      - TZ=Asia/Shanghai
    command:
      --requirepass "xxx"
    ports:
      - 6379:6379
#    expose:
#      - 6379
    privileged: true #容器内的root权限等于宿主机root
    restart: always
    networks:
      - "net1"

networks:
  net1:
    external:
      name: mynetwork
复制代码

 

 

创建Asp.Net Core项目

创建一个默认的Blazor Server项目做测试。

NuGet安装

    <PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="7.0.5" />

startup注册分布式缓存服务

        services.AddStackExchangeRedisCache(options => options.Configuration = configuration.GetConnectionString("redisServerUrl"));

本地调试appsettings.Development.json连接字符串访问域名

  "ConnectionStrings": {

    "redisServerUrl": "www.myweb.com:6379,password=xxx"

  }

发布到云服务器,在同一个docker网桥里边,appsettings.json连接字符串访问容器名

  "ConnectionStrings": {

    "redisServerUrl": "redis:6379,password=xxx"

  },

 

编写读写缓存辅助函数

参考《使用 Redis ASP.Net Core 中进行分布式缓存_redis_weixin_0010034-DevPress官方社区》,编写读写缓存辅助函数。

 

复制代码
public static class DistributedCacheExtensions
{

    #region Redis分布式缓存

    /// <summary>
    /// 从分布式缓存获取对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="cache"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static async Task<T?> GetCacheValueAsync<T>(this IDistributedCache cache, string key) where T : class
    {
        var result = await cache.GetStringAsync(key);
        if (string.IsNullOrEmpty(result))
            return null;

        var deserializedObj = JsonConvert.DeserializeObject<T>(result);

        return deserializedObj;
    }

    /// <summary>
    /// 把对象保存到分布式缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="cache"></param>
    /// <param name="key"></param>
    /// <param name="value">待保存的对象,可以为null</param>
    /// <param name="expireTimeLen">缓存时长,单位:秒,默认3600秒</param>
    /// <returns></returns>
    public static async Task SetCacheValueAsync<T>(this IDistributedCache cache, string key, T? value, int expireTimeLen = 3600) where T : class
    {
        var cacheEntryOptions = new DistributedCacheEntryOptions();

        // Remove item from cache after duration
        cacheEntryOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(expireTimeLen);

        // Remove item from cache if unsued for the duration
        //cacheEntryOptions.SlidingExpiration = TimeSpan.FromSeconds(30);

        string result = (value is not null) ? JsonConvert.SerializeObject(value) : "";

        await cache.SetStringAsync(key, result, cacheEntryOptions);
    }

    #endregion
}
复制代码

 

 

读写缓存

Asp.Net Core项目中需要访问分布式缓存的对象,构造注入IDistributedCache即可。

 

复制代码
private const string weatherKey = "weatherResult";

        private readonly IDistributedCache _cache;

        public WeatherForecastService(IDistributedCache cache)
        {
            _cache = cache;
        }

        public async Task<WeatherForecast[]> GetForecastAsync(DateOnly startDate)
        {
            var ary = await _cache.GetCacheValueAsync<WeatherForecast[]>(weatherKey);
            if (ary is null)
            {

                ary = Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = startDate.AddDays(index),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                })
                   .ToArray();

                await _cache.SetCacheValueAsync(weatherKey, ary, 60);
            }

            return ary;
        }
复制代码

 

 

查看redis容器缓存内容

从宿主机进入redis容器

# docker exec -it redis /bin/sh

 

在容器里边连接redis

/ # redis-cli -h 127.0.0.1 -p 6379

 

如果redis设置了密码,要使用auth命令输入密码,否则提示需要认证

127.0.0.1:6379> keys *

(error) NOAUTH Authentication required.

127.0.0.1:6379> auth xxx

OK

127.0.0.1:6379> keys *

1) "weatherResult"

 

删除key

127.0.0.1:6379> del weatherResult

(integer) 1

127.0.0.1:6379> keys *

(empty array)

 

查看key的剩余有效期,-2就是过期删除了

127.0.0.1:6379> ttl weatherResult

(integer) 6

127.0.0.1:6379> ttl weatherResult

(integer) -2

 

退出redis后,再提出容器

127.0.0.1:6379> exit

/ # exit

 

posted on   SunnyTrudeau  阅读(295)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示