ASP.NET Core 使用 Redis 客户端
Mac OS 安装 Redis(用于连 Redis 服务器,方便查看数据):https://redis.io/topics/quickstart
wget http://download.redis.io/redis-stable.tar.gz(没有wget命令,手动下载)tar xvzf redis-stable.tar.gzcd redis-stablemakesudo make installmake 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
参考资料:
- redis-cli, the Redis command line interface
 - MAC下 安装 redis
 - Redis 常用命令
 - StackExchange.Redis ConnectionMultiplexer.Connect() Intermittently Works
 - StackExchange.Redis simple C# Example
 - Redis Cache in ASP.NET Core
 - Using Redis Cache in .net Core
 - redis 报Operation against a key holding the wrong kind of value 警告的解决方法
 
微信公众号:你好架构
出处:http://www.cnblogs.com/xishuai/
公众号会不定时的分享有关架构的方方面面,包含并不局限于:Microservices(微服务)、Service Mesh(服务网格)、DDD/TDD、Spring Cloud、Dubbo、Service Fabric、Linkerd、Envoy、Istio、Conduit、Kubernetes、Docker、MacOS/Linux、Java、.NET Core/ASP.NET Core、Redis、RabbitMQ、MongoDB、GitLab、CI/CD(持续集成/持续部署)、DevOps等等。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。


                
            
        
浙公网安备 33010602011771号