garnet

Форк
0
/
GarnetClientSamples.cs 
283 строки · 9.4 Кб
1
// Copyright (c) Microsoft Corporation.
2
// Licensed under the MIT license.
3

4
using System;
5
using System.Net.Security;
6
using System.Security.Cryptography.X509Certificates;
7
using System.Text;
8
using System.Threading;
9
using System.Threading.Tasks;
10
using Garnet.client;
11

12
namespace GarnetClientSample
13
{
14
    /// <summary>
15
    /// Use Garnet with GarnetClient as client library
16
    /// </summary>
17
    public class GarnetClientSamples
18
    {
19
        readonly string address;
20
        readonly int port;
21
        readonly bool useTLS;
22

23
        public GarnetClientSamples(string address, int port, bool useTLS)
24
        {
25
            this.address = address;
26
            this.port = port;
27
            this.useTLS = useTLS;
28
        }
29

30
        public async Task RunAll()
31
        {
32
            await PingAsync();
33
            await SetGetAsync();
34
            SetGetSync();
35
            await IncrAsync();
36
            await IncrByAsync(99);
37
            await DecrByAsync(99);
38
            await DecrAsync("test", 5);
39
            await IncrNoKeyAsync();
40
            await ExistsAsync();
41
            await DeleteAsync();
42
            await SetGetMemoryAsync();
43
        }
44

45
        async Task PingAsync()
46
        {
47
            using var db = new GarnetClient(address, port, GetSslOpts());
48
            await db.ConnectAsync();
49
            var pong = await db.PingAsync();
50
            if (pong != "PONG")
51
                throw new Exception("PingAsync: Error");
52
            Console.WriteLine("Ping: Success");
53
        }
54

55
        async Task SetGetAsync()
56
        {
57
            using var db = new GarnetClient(address, port, GetSslOpts());
58
            await db.ConnectAsync();
59

60
            string origValue = "abcdefg";
61
            await db.StringSetAsync("mykey", origValue);
62

63
            string retValue = await db.StringGetAsync("mykey");
64

65
            if (origValue != retValue)
66
                throw new Exception("SetGetAsync: Error");
67
            Console.WriteLine("SetGetAsync: Success");
68
        }
69

70
        void SetGetSync()
71
        {
72
            using var db = new GarnetClient(address, port, GetSslOpts());
73
            db.Connect();
74

75
            string origValue = "abcdefg";
76
            db.StringSet("mykey", origValue, (c, s) => { if (s != "OK") throw new Exception("SetGetSync: Error"); });
77

78
            ManualResetEventSlim e = new();
79
            db.StringGet("mykey", (c, s) => { if (s != origValue) throw new Exception("SetGetSync: Error"); e.Set(); });
80
            e.Wait();
81
            Console.WriteLine("SetGetSync: Success");
82
        }
83

84
        async Task IncrAsync()
85
        {
86
            using var db = new GarnetClient(address, port, GetSslOpts());
87
            await db.ConnectAsync();
88

89
            // Key storing integer
90
            int nVal = 1000;
91
            var strKey = "key1";
92
            await db.StringSetAsync(strKey, $"{nVal}");
93
            var s = await db.StringGetAsync(strKey);
94

95
            if (s != $"{nVal}")
96
                throw new Exception("IncrementAsync: Error");
97

98
            long n = await db.StringIncrement(strKey);
99
            if (n != nVal + 1)
100
                throw new Exception("IncrementAsync: Error");
101

102
            int nRetVal = int.Parse(await db.StringGetAsync(strKey));
103
            if (n != nRetVal)
104
                throw new Exception("IncrementAsync: Error");
105
            Console.WriteLine("IncrementAsync: Success");
106
        }
107

108
        async Task IncrByAsync(long nIncr)
109
        {
110
            using var db = new GarnetClient(address, port, GetSslOpts());
111
            await db.ConnectAsync();
112

113
            // Key storing integer
114
            int nVal = 1000;
115

116
            var strKey = "key1";
117
            await db.StringSetAsync(strKey, $"{nVal}");
118
            var s = await db.StringGetAsync(strKey);
119

120
            if (s != $"{nVal}")
121
                throw new Exception("IncrementByAsync: Error");
122

123
            long n = int.Parse(await db.ExecuteForStringResultAsync("INCRBY", new string[] { strKey, nIncr.ToString() }));
124
            if (n != nVal + nIncr)
125
                throw new Exception("IncrementByAsync: Error");
126

127
            int nRetVal = int.Parse(await db.StringGetAsync(strKey));
128
            if (n != nRetVal)
129
                throw new Exception("IncrementByAsync: Error");
130
            Console.WriteLine("IncrementByAsync: Success");
131
        }
132

133
        async Task DecrByAsync(long nDecr)
134
        {
135
            using var db = new GarnetClient(address, port, GetSslOpts());
136
            await db.ConnectAsync();
137

138
            // Key storing integer
139
            int nVal = 900;
140

141
            var strKey = "key1";
142
            await db.StringSetAsync(strKey, $"{nVal}");
143
            var s = await db.StringGetAsync(strKey);
144

145
            if (s != $"{nVal}")
146
                throw new Exception("DecrByAsync: Error");
147

148
            long n = int.Parse(await db.ExecuteForStringResultAsync("DECRBY", new string[] { strKey, nDecr.ToString() }));
149
            if (n != nVal - nDecr)
150
                throw new Exception("DecrByAsync: Error");
151

152
            int nRetVal = int.Parse(await db.StringGetAsync(strKey));
153
            if (n != nRetVal)
154
                throw new Exception("DecrByAsync: Error");
155
            Console.WriteLine("DecrByAsync: Success");
156
        }
157

158
        async Task DecrAsync(string strKey, int nVal)
159
        {
160
            using var db = new GarnetClient(address, port, GetSslOpts());
161
            await db.ConnectAsync();
162

163
            await db.StringSetAsync(strKey, $"{nVal}");
164
            var s = await db.StringGetAsync(strKey);
165

166
            if (s != $"{nVal}")
167
                throw new Exception("DecrAsync: Error");
168

169
            long n = await db.StringDecrement(strKey);
170
            if (n != nVal - 1)
171
                throw new Exception("DecrAsync: Error");
172

173
            int nRetVal = int.Parse(await db.StringGetAsync(strKey));
174
            if (n != nRetVal)
175
                throw new Exception("DecrAsync: Error");
176
            Console.WriteLine("DecrAsync: Success");
177
        }
178

179
        async Task IncrNoKeyAsync()
180
        {
181
            using var db = new GarnetClient(address, port, GetSslOpts());
182
            await db.ConnectAsync();
183

184
            // Key storing integer
185
            var strKey = "key1";
186
            int init = int.Parse(await db.StringGetAsync(strKey));
187
            await db.StringIncrement(strKey);
188

189
            var retVal = int.Parse(await db.StringGetAsync(strKey));
190

191
            await db.StringIncrement(strKey);
192
            retVal = int.Parse(await db.StringGetAsync(strKey));
193

194
            if (init + 2 != retVal)
195
                throw new Exception("IncrNoKeyAsync: Error");
196
            Console.WriteLine("IncrNoKeyAsync: Success");
197
        }
198

199
        async Task ExistsAsync()
200
        {
201
            using var db = new GarnetClient(address, port, GetSslOpts());
202
            await db.ConnectAsync();
203

204
            // Key storing integer
205
            int nVal = 100;
206
            var strKey = "key1";
207
            await db.StringSetAsync(strKey, $"{nVal}");
208

209
            bool fExists = int.Parse(await db.ExecuteForStringResultAsync("EXISTS", new string[] { strKey })) == 1 ? true : false;
210
            if (!fExists)
211
                throw new Exception("ExistsAsync: Error");
212
            Console.WriteLine("ExistsAsync: Success");
213
        }
214

215
        async Task DeleteAsync()
216
        {
217
            using var db = new GarnetClient(address, port, GetSslOpts());
218
            await db.ConnectAsync();
219

220
            // Key storing integer
221
            var nVal = 100;
222
            var strKey = "key1";
223
            await db.StringSetAsync(strKey, $"{nVal}");
224
            await db.KeyDeleteAsync(strKey);
225

226
            bool fExists = int.Parse(await db.ExecuteForStringResultAsync("EXISTS", new string[] { strKey })) == 1 ? true : false;
227
            if (fExists)
228
                throw new Exception("DeleteAsync: Error");
229
            Console.WriteLine("DeleteAsync: Success");
230
        }
231

232

233
        async Task SetGetMemoryAsync()
234
        {
235
            using var db = new GarnetClient(address, port, GetSslOpts());
236
            await db.ConnectAsync();
237

238
            var key = new Memory<byte>(new byte[17]);
239
            Encoding.UTF8.GetBytes("SetGetMemoryAsync".AsSpan(), key.Span);
240

241
            var origValueStr = "abcdefg";
242
            var origValue = new Memory<byte>(new byte[7]);
243
            Encoding.UTF8.GetBytes(origValueStr.AsSpan(), origValue.Span);
244

245
            await db.StringSetAsync(key, origValue);
246

247
            using var retValue = await db.StringGetAsMemoryAsync(key);
248

249
            if (!origValue.Span.SequenceEqual(retValue.Span))
250
                throw new Exception("SetGetAsync: Error");
251

252
            Console.WriteLine("SetGetMemoryAsync: Success");
253
        }
254

255
        SslClientAuthenticationOptions GetSslOpts() => useTLS ? new()
256
        {
257
            ClientCertificates = [new X509Certificate2("testcert.pfx", "placeholder")],
258
            TargetHost = "GarnetTest",
259
            RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
260
        } : null;
261

262
        public void ConnectionStressTest()
263
        {
264
            for (int t = 0; t < 8; t++)
265
            {
266
                new Thread(() => ConnectionStressRunner(t)).Start();
267
            }
268
            Thread.Sleep(Timeout.Infinite);
269

270
            void ConnectionStressRunner(int thread_id)
271
            {
272
                int i = 0;
273
                while (true)
274
                {
275
                    using var client = new GarnetClient(address, port, GetSslOpts());
276
                    client.Connect();
277
                    Console.WriteLine($"{thread_id}:{i++}: {client.PingAsync().GetAwaiter().GetResult()}");
278
                    client.Dispose();
279
                }
280
            }
281
        }
282
    }
283
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.