zoukankan      html  css  js  c++  java
  • ASP.NET Core 使用 Redis 客户端

    Mac OS 安装 Redis(用于连 Redis 服务器,方便查看数据):https://redis.io/topics/quickstart

    1. wget http://download.redis.io/redis-stable.tar.gz(没有wget命令,手动下载)
    2. tar xvzf redis-stable.tar.gz
    3. cd redis-stable
    4. make
    5. sudo make install
    6. make test(测试安装是否成功)

    安装好之后,我们就可以使用redis-cli命令了,

    连接 Redis 服务器:

    $ redis-cli -h 12.22.10.33 -p 6379 -a "password"
    12.22.10.33:6379> ping
    PONG
    

    查看 key 是否存在(1 表示存在):

    $ exists test_key
    (integer) 1
    

    查看指定 key 的值类型:

    $ type test_key
    string
    

    获取指定 key 的字符串值:

    $ get test_key
    "hello world"
    

    上面是一些简单的redis-cli命令,更多命令查看:http://www.runoob.com/redis/redis-commands.html


    ASP.NET Core 使用 Redis 客户端,最好的选择当然是 StackExchange.Redis,GitHub 地址:https://github.com/StackExchange/StackExchange.Redis

    使用很简单,首先安装程序包:

    PM> Install-Package StackExchange.Redis
    

    使用简单示例:

    static void Main(string[] args)
    {
        //var configurationOptions = new ConfigurationOptions
        //{
        //    EndPoints =
        //    {
        //        "10.11.22.1", "6379",
        //        "10.11.22.2", "6379",
        //        "10.11.22.3", "6379"
        //    },
        //    Password = "aqsea3491"
        //};
        ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("10.11.22.1:6379,10.11.22.1:6379,10.11.22.1:6379,password=123456");
        IDatabase db = redis.GetDatabase();
        string value = "abcdefg";
        db.StringSet("test_key", value);
    
        value = db.StringGet("test_key");
    
        Console.WriteLine(value);
        Console.ReadLine();
    }
    

    当然,如果用于生产环境的话,需要再进行封装下,如果我们使用的是 ASP.NET Core 的话,还有一种不用自己封装的选择,那就是 Microsoft.Extensions.Caching.Redis,GitHub 地址:https://github.com/aspnet/Caching/tree/dev/src/Microsoft.Extensions.Caching.Redis

    Microsoft.Extensions.Caching.Redis 是微软自己封装的 Redis 组件,内部使用的还是 StackExchange.Redis,但在 ASP.NET Core 中使用起来,非常简单。

    首先安装程序包:

    PM> Microsoft.Extensions.Caching.Redis
    

    Startup.ConfigureServices配置:

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
    
        // For redis
        // install-package Microsoft.Extensions.Caching.Redis
        services.AddDistributedRedisCache(options =>
        {
            options.InstanceName = "";
            options.Configuration = "10.11.22.1:6379,10.11.22.1:6379,10.11.22.1:6379,password=123456";
        });
    }
    

    简单使用:

    public class ValuesController : Controller
    {
        private readonly IDistributedCache _distributedCache;
    
        public ValuesController(IDistributedCache distributedCache)
        {
            _distributedCache = distributedCache;
        }
    
        // GET api/values
        [HttpGet]
        public async Task<string> Get()
        {
            // redis operate
            var key = "test_key";
            var valueByte = await _distributedCache.GetAsync(key);
            if (valueByte == null)
            {
                await _distributedCache.SetAsync(key, Encoding.UTF8.GetBytes("world22222"), new DistributedCacheEntryOptions().SetSlidingExpiration(DateTimeOffset.Now.AddSeconds(3000)));
                valueByte = await _distributedCache.GetAsync(key);
            }
            var valueString = Encoding.UTF8.GetString(valueByte);
            return valueString;
        }
    }
    

    测试过程中,发现 Microsoft.Extensions.Caching.Redis 有一个问题,虽然IDistributedCache提供了SetStringAsync方法,但实际插入到 Redis 的值类型,并不是string,而是hash,可以用redis-cli命令进行测试:

    114.55.56.213:6379> get test_key
    (error) WRONGTYPE Operation against a key holding the wrong kind of value
    114.55.56.213:6379> type test_key
    hash
    

    所以,没办法,只能使用SetAsync,然后读取再由byte转换为string

    另外,微软封装的Caching,除了 Microsoft.Extensions.Caching.Redis,还有:

    • Microsoft.Extensions.Caching.Abstractions
    • Microsoft.Extensions.Caching.Memory
    • Microsoft.Extensions.Caching.SqlServer(使用 SqlServer 数据库,作为缓存存储)

    详细使用,请查看:Working with a distributed cache

    参考资料:

  • 相关阅读:
    Opencv(1)介绍篇
    植被覆盖度制图
    GIS应用开发AO(2)-空间分析ITopologicalOperate
    GIS应用开发AO(1)_普通几何图形绘制
    初识机器学习-人脸识别
    ArcGIS API for javascript4.3——RouteTask
    javascript学习(1)随机点名应用
    生活感悟之六
    生活感悟之五
    生活感悟之四
  • 原文地址:https://www.cnblogs.com/xishuai/p/asp-net-core-use-redis.html
Copyright © 2011-2022 走看看