Nedenfor er et simpelt eksempel for at give dig en smagsprøve på, hvor nemt det er at bruge nogle af Redis' avancerede datastrukturer - i dette tilfælde Redis Lists:Fuld kildekode til dette eksempel kan ses online
using var redisClient = new RedisClient();
//Create a 'strongly-typed' API that makes all Redis Value operations to apply against Shippers
IRedisTypedClient<Shipper> redis = redisClient.As<Shipper>();
//Redis lists implement IList<T> while Redis sets implement ICollection<T>
var currentShippers = redis.Lists["urn:shippers:current"];
var prospectiveShippers = redis.Lists["urn:shippers:prospective"];
currentShippers.Add(
new Shipper {
Id = redis.GetNextSequence(),
CompanyName = "Trains R Us",
DateCreated = DateTime.UtcNow,
ShipperType = ShipperType.Trains,
UniqueRef = Guid.NewGuid()
});
currentShippers.Add(
new Shipper {
Id = redis.GetNextSequence(),
CompanyName = "Planes R Us",
DateCreated = DateTime.UtcNow,
ShipperType = ShipperType.Planes,
UniqueRef = Guid.NewGuid()
});
var lameShipper = new Shipper {
Id = redis.GetNextSequence(),
CompanyName = "We do everything!",
DateCreated = DateTime.UtcNow,
ShipperType = ShipperType.All,
UniqueRef = Guid.NewGuid()
};
currentShippers.Add(lameShipper);
Dump("ADDED 3 SHIPPERS:", currentShippers);
currentShippers.Remove(lameShipper);
Dump("REMOVED 1:", currentShippers);
prospectiveShippers.Add(
new Shipper {
Id = redis.GetNextSequence(),
CompanyName = "Trucks R Us",
DateCreated = DateTime.UtcNow,
ShipperType = ShipperType.Automobiles,
UniqueRef = Guid.NewGuid()
});
Dump("ADDED A PROSPECTIVE SHIPPER:", prospectiveShippers);
redis.PopAndPushBetweenLists(prospectiveShippers, currentShippers);
Dump("CURRENT SHIPPERS AFTER POP n' PUSH:", currentShippers);
Dump("PROSPECTIVE SHIPPERS AFTER POP n' PUSH:", prospectiveShippers);
var poppedShipper = redis.PopFromList(currentShippers);
Dump("POPPED a SHIPPER:", poppedShipper);
Dump("CURRENT SHIPPERS AFTER POP:", currentShippers);
//reset sequence and delete all lists
redis.SetSequence(0);
redis.Remove(currentShippers, prospectiveShippers);
Dump("DELETING CURRENT AND PROSPECTIVE SHIPPERS:", currentShippers);
EKSEMPEL OUTPUT:
ADDED 3 SHIPPERS:
Id:1,CompanyName:Trains R Us,ShipperType:Trains,DateCreated:2010-01-31T11:53:37.7169323Z,UniqueRef:d17c5db0415b44b2ac5da7b6ebd780f5
Id:2,CompanyName:Planes R Us,ShipperType:Planes,DateCreated:2010-01-31T11:53:37.799937Z,UniqueRef:e02a73191f4b4e7a9c44eef5b5965d06
Id:3,CompanyName:We do everything!,ShipperType:All,DateCreated:2010-01-31T11:53:37.8009371Z,UniqueRef:d0c249bbbaf84da39fc4afde1b34e332
REMOVED 1:
Id:1,CompanyName:Trains R Us,ShipperType:Trains,DateCreated:2010-01-31T11:53:37.7169323Z,UniqueRef:d17c5db0415b44b2ac5da7b6ebd780f5
Id:2,CompanyName:Planes R Us,ShipperType:Planes,DateCreated:2010-01-31T11:53:37.799937Z,UniqueRef:e02a73191f4b4e7a9c44eef5b5965d06
ADDED A PROSPECTIVE SHIPPER:
Id:4,CompanyName:Trucks R Us,ShipperType:Automobiles,DateCreated:2010-01-31T11:53:37.8539401Z,UniqueRef:67d7d4947ebc4b0ba5c4d42f5d903bec
CURRENT SHIPPERS AFTER POP n' PUSH:
Id:4,CompanyName:Trucks R Us,ShipperType:Automobiles,DateCreated:2010-01-31T11:53:37.8539401Z,UniqueRef:67d7d4947ebc4b0ba5c4d42f5d903bec
Id:1,CompanyName:Trains R Us,ShipperType:Trains,DateCreated:2010-01-31T11:53:37.7169323Z,UniqueRef:d17c5db0415b44b2ac5da7b6ebd780f5
Id:2,CompanyName:Planes R Us,ShipperType:Planes,DateCreated:2010-01-31T11:53:37.799937Z,UniqueRef:e02a73191f4b4e7a9c44eef5b5965d06
PROSPECTIVE SHIPPERS AFTER POP n' PUSH:
POPPED a SHIPPER:
Id:2,CompanyName:Planes R Us,ShipperType:Planes,DateCreated:2010-01-31T11:53:37.799937Z,UniqueRef:e02a73191f4b4e7a9c44eef5b5965d06
CURRENT SHIPPERS AFTER POP:
Id:4,CompanyName:Trucks R Us,ShipperType:Automobiles,DateCreated:2010-01-31T11:53:37.8539401Z,UniqueRef:67d7d4947ebc4b0ba5c4d42f5d903bec
Id:1,CompanyName:Trains R Us,ShipperType:Trains,DateCreated:2010-01-31T11:53:37.7169323Z,UniqueRef:d17c5db0415b44b2ac5da7b6ebd780f5
DELETING CURRENT AND PROSPECTIVE SHIPPERS:
Flere eksempler er tilgængelige på [RedisExamples Redis-eksempler-siden] og i den omfattende testsuite
Hastighed #
En af de bedste ting ved Redis er hastigheden - den er hurtig.
Dette eksempel nedenfor gemmer og henter hele Northwind-databasen (3202 poster) på mindre 1,2 sek - vi har aldrig haft det så hurtigt!
(Kører i en VS.NET/R#-enhedstest på en 3 år gammel iMac)
using var client = new RedisClient();
var before = DateTime.Now;
client.StoreAll(NorthwindData.Categories);
client.StoreAll(NorthwindData.Customers);
client.StoreAll(NorthwindData.Employees);
client.StoreAll(NorthwindData.Shippers);
client.StoreAll(NorthwindData.Orders);
client.StoreAll(NorthwindData.Products);
client.StoreAll(NorthwindData.OrderDetails);
client.StoreAll(NorthwindData.CustomerCustomerDemos);
client.StoreAll(NorthwindData.Regions);
client.StoreAll(NorthwindData.Territories);
client.StoreAll(NorthwindData.EmployeeTerritories);
Console.WriteLine("Took {0}ms to store the entire Northwind database ({1} records)",
(DateTime.Now - before).TotalMilliseconds, totalRecords);
before = DateTime.Now;
var categories = client.GetAll<Category>();
var customers = client.GetAll<Customer>();
var employees = client.GetAll<Employee>();
var shippers = client.GetAll<Shipper>();
var orders = client.GetAll<Order>();
var products = client.GetAll<Product>();
var orderDetails = client.GetAll<OrderDetail>();
var customerCustomerDemos = client.GetAll<CustomerCustomerDemo>();
var regions = client.GetAll<Region>();
var territories = client.GetAll<Territory>();
var employeeTerritories = client.GetAll<EmployeeTerritory>();
Console.WriteLine("Took {0}ms to get the entire Northwind database ({1} records)",
(DateTime.Now - before).TotalMilliseconds, totalRecords);
/*
== EXAMPLE OUTPUT ==
Took 1020.0583ms to store the entire Northwind database (3202 records)
Took 132.0076ms to get the entire Northwind database (3202 records)
*/
Bemærk:Den samlede tid, det tager, inkluderer en ekstra Redis-operation for hver post for at gemme id'et i et Redis-sæt for hver type samt serialisering og de-serialisering af hver post ved hjælp af Service Stacks TypeSerializer.
Lex Operations #
De nye ZRANGEBYLEX-sorterede sæt-operationer, der giver dig mulighed for at forespørge på et sorteret sæt leksikalsk, er blevet tilføjet. Et godt udstillingsvindue for dette er tilgængeligt på autocomplete.redis.io.
Disse nye operationer er tilgængelige som en 1:1 mapping med redis-server på IRedisNativeClient
:
public interface IRedisNativeClient
{
...
byte[][] ZRangeByLex(string setId, string min, string max, int? skip, int? take);
long ZLexCount(string setId, string min, string max);
long ZRemRangeByLex(string setId, string min, string max);
}
Og de mere brugervenlige API'er under IRedisClient
:
public interface IRedisClient
{
...
List<string> SearchSortedSet(string setId, string start=null, string end=null);
long SearchSortedSetCount(string setId, string start=null, string end=null);
long RemoveRangeFromSortedSetBySearch(string setId, string start=null, string end=null);
}
Ligesom NuGet version matchers, bruger Redis [
char for at udtrykke rummelighed og (
char for eksklusivitet. Siden IRedisClient
API'er er som standard inkluderende søgninger, disse to API'er er de samme:
Redis.SearchSortedSetCount("zset", "a", "c")
Redis.SearchSortedSetCount("zset", "[a", "[c")
Alternativt kan du angive en eller begge grænser til at være eksklusive ved at bruge (
præfiks, f.eks.:
Redis.SearchSortedSetCount("zset", "a", "(c")
Redis.SearchSortedSetCount("zset", "(a", "(c")
Flere API-eksempler er tilgængelige i LexTests.cs.
HyperLog API #
Udviklingsgrenen af Redis server (tilgængelig, når v3.0 frigives) inkluderer en genial algoritme til at tilnærme de unikke elementer i et sæt med maksimal plads- og tidseffektivitet. For detaljer om, hvordan det fungerer, se Redis' skaber Salvatores blog, som forklarer det meget detaljeret. I bund og grund giver det dig mulighed for at opretholde en effektiv måde at tælle og flette unikke elementer i et sæt uden at skulle gemme dets elementer. Et simpelt eksempel på det i aktion:
redis.AddToHyperLog("set1", "a", "b", "c");
redis.AddToHyperLog("set1", "c", "d");
var count = redis.CountHyperLog("set1"); //4
redis.AddToHyperLog("set2", "c", "d", "e", "f");
redis.MergeHyperLogs("mergedset", "set1", "set2");
var mergeCount = redis.CountHyperLog("mergedset"); //6
Scan API'er #
Redis v2.8 introducerede en smuk ny SCAN-operation, der giver en optimal strategi til at krydse en redis-forekomst af hele nøglesættet i håndterbare bidder, der kun bruger en markør på klientsiden og uden at introducere nogen servertilstand. Det er et alternativ med højere ydeevne og bør bruges i stedet for NØGLER i applikationskoden. SCAN og dets relaterede operationer til at krydse medlemmer af sæt, sorterede sæt og hashes er nu tilgængelige i Redis-klienten i følgende API'er:
public interface IRedisClient
{
...
IEnumerable<string> ScanAllKeys(string pattern = null, int pageSize = 1000);
IEnumerable<string> ScanAllSetItems(string setId, string pattern = null, int pageSize = 1000);
IEnumerable<KeyValuePair<string, double>> ScanAllSortedSetItems(string setId, string pattern = null, int pageSize = 1000);
IEnumerable<KeyValuePair<string, string>> ScanAllHashEntries(string hashId, string pattern = null, int pageSize = 1000);
}
public interface IRedisClientAsync
{
IAsyncEnumerable<string> ScanAllKeysAsync(string pattern = null, int pageSize, CancellationToken ct);
IAsyncEnumerable<string> ScanAllSetItemsAsync(string setId, string pattern = null, int pageSize, CancellationToken ct);
IAsyncEnumerable<KeyValuePair<string, double>> ScanAllSortedSetItemsAsync(string setId, string pattern = null, int pageSize, ct);
IAsyncEnumerable<KeyValuePair<string, string>> ScanAllHashEntriesAsync(string hashId, string pattern = null, int pageSize, ct);
}
//Low-level API
public interface IRedisNativeClient
{
...
ScanResult Scan(ulong cursor, int count = 10, string match = null);
ScanResult SScan(string setId, ulong cursor, int count = 10, string match = null);
ScanResult ZScan(string setId, ulong cursor, int count = 10, string match = null);
ScanResult HScan(string hashId, ulong cursor, int count = 10, string match = null);
}
public interface IRedisNativeClientAsync
{
ValueTask<ScanResult> ScanAsync(ulong cursor, int count = 10, string match = null, CancellationToken ct);
ValueTask<ScanResult> SScanAsync(string setId, ulong cursor, int count = 10, string match = null, CancellationToken ct);
ValueTask<ScanResult> ZScanAsync(string setId, ulong cursor, int count = 10, string match = null, CancellationToken ct);
ValueTask<ScanResult> HScanAsync(string hashId, ulong cursor, int count = 10, string match = null, CancellationToken ct);
}
IRedisClient
leverer en API på højere niveau, der abstraherer klientmarkøren for at afsløre en doven Enumerable-sekvens for at give en optimal måde at streame scannede resultater på, der integreres pænt med LINQ, f.eks.:
var scanUsers = Redis.ScanAllKeys("urn:User:*");
var sampleUsers = scanUsers.Take(10000).ToList(); //Stop after retrieving 10000 user keys