Get started with Redis

环境说明

* Redis Server: Hyper-V, Ubuntu 18.04, 2GB RAM
* Redis Client: Hyper-V, Ubuntu 18.04, 1GB RAM
* Visual Studio 2017

安装并配置 redis 服务

1. 安装 redis-server
$ sudo apt-get install redis-server

$ redis-server --version
Redis server v=4.0.9 sha=00000000:0 malloc=jemalloc-3.6.0 bits=64 build=9435c3c2879311f3

2. 验证安装
$ redis-cli
127.0.0.1:6379>

3. 配置高强度的密码
$ sudo vim /etc/redis/redis.conf
找到 requirepass,设置一个高强度的密码

4. 设置绑定地址
找到 bind 属性
设置为 bind 127.0.0.1 ::1 [IP1] [IP2] [IP3] ...
或者为 bind 0.0.0.0,表示绑定所有的 interface

5. 重启服务
$ sudo service redis restart

6. 本地验证,在 redis 服务器上验证
$ redis-cli
127.0.0.1:6379> AUTH ****
OK

7. 远程验证
C:\telnet [redis-server-ip] 6379
AUTH ****
+OK

测试性能,用如下命令

$ redis-benchmark -h [HOST] -a [PASSWORD] -c 50 -n 100000 -d 2048
...
====== SET ======
  100000 requests completed in 1.73 seconds
  50 parallel clients
  2048 bytes payload
  keep alive: 1

87.27% <= 1 milliseconds
99.90% <= 2 milliseconds
99.98% <= 3 milliseconds
100.00% <= 3 milliseconds
57670.13 requests per second

====== GET ======
  100000 requests completed in 1.43 seconds
  50 parallel clients
  2048 bytes payload
  keep alive: 1

97.89% <= 1 milliseconds
99.99% <= 2 milliseconds
100.00% <= 2 milliseconds
69686.41 requests per second
...

程序化访问,由于ServiceStack.Redis存在以下限制,所以采用StackExchange.Redis

The ServiceStack.Redis NuGet package include the following limitations:

10 Operations in ServiceStack (i.e. Request DTOs)
10 Tables in OrmLite
20 Different Types in JSON, JSV and CSV Serializers *
20 Different Types in Redis Client Typed APIs
6000 requests per hour with the Redis Client
static void TestStringSet(IDatabase db)
{
    using (new TickCounter()) {
        var q = Enumerable.Range(0, 100000).Select(i => db.StringSetAsync(string.Format("P{0:000}", i), $"Patient {i}"));
        Task.WaitAll(q.ToArray());
    }
}
Time cost 00:00:00.2670376 for Program.TestStringSet()
static void TestStringGetAsync(IDatabase db)
{
    var dict = new ConcurrentDictionary<int, RedisValue>();
    using (new TickCounter()) {
        var q = Enumerable.Range(0, 100000).Select(i => db.StringGetAsync(string.Format("P{0:000}", i)).ContinueWith(t => dict[i] = t.Result));
        Task.WaitAll(q.ToArray());
    }
    Console.WriteLine(dict[90000]);
}
Time cost 00:00:00.4040716 for Program.TestStringGetAsync()
static void TestStringGetSync(IDatabase db)
{
    var dict = new Dictionary<int, RedisValue>();
    using (new TickCounter()) {
        for (int i = 0; i < 100000; i++) {
            var x = db.StringGet(string.Format("P{0:000}", i));
            dict[i] = x;
        }
    }
    Console.WriteLine(dict[90000]);
}
Time cost 00:00:15.7089098 for Program.TestStringGetSync()

用命令行测试,可以正常打开图片

$ redis-cli -h [HOST] -a [PASSWORD] --raw get 'img1' > cc.jpg