sql >> Base de Datos >  >> NoSQL >> Redis

Primeros pasos con las API de cliente de Redis

A continuación se muestra un ejemplo simple para darle una idea de lo fácil que es usar algunas de las estructuras de datos avanzadas de Redis; en este caso, Redis Lists:El código fuente completo de este ejemplo se puede ver en línea

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);

SALIDA DE EJEMPLO:

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:

Hay más ejemplos disponibles en la [página de ejemplos de RedisExamples Redis] y en el conjunto de pruebas completo

Velocidad #

Una de las mejores cosas de Redis es la velocidad:es rápido.

Este ejemplo a continuación almacena y obtiene toda la base de datos de Northwind (3202 registros) en menos de 1,2 segundos - ¡nunca lo habíamos tenido tan rápido!

(Ejecución dentro de una prueba de unidad VS.NET/R# en un iMac de 3 años)

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)
*/

Nota:El tiempo total empleado incluye una operación de Redis adicional para cada registro para almacenar la identificación en un conjunto de Redis para cada tipo, además de serializar y deserializar cada registro mediante TypeSerializer de Service Stack.

Operaciones lex #

Se han agregado las nuevas operaciones de conjuntos ordenados ZRANGEBYLEX que le permiten consultar un conjunto ordenado léxicamente. Un buen escaparate para esto está disponible en autocomplete.redis.io.

Estas nuevas operaciones están disponibles como mapeo 1:1 con redis-server en 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);
}

Y las API más fáciles de usar en 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);
}

Al igual que los comparadores de versiones de NuGet, Redis usa [ char para expresar inclusión y ( char por exclusividad. Desde el IRedisClient Las API están predeterminadas para búsquedas inclusivas, estas dos API son iguales:

Redis.SearchSortedSetCount("zset", "a", "c")
Redis.SearchSortedSetCount("zset", "[a", "[c")

Alternativamente, puede especificar uno o ambos límites para que sean exclusivos usando el ( prefijo, por ejemplo:

Redis.SearchSortedSetCount("zset", "a", "(c")
Redis.SearchSortedSetCount("zset", "(a", "(c")

Hay más ejemplos de API disponibles en LexTests.cs.

Número de API de HyperLog

La rama de desarrollo del servidor Redis (disponible cuando se lanza v3.0) incluye un ingenioso algoritmo para aproximar los elementos únicos en un conjunto con la máxima eficiencia de espacio y tiempo. Para obtener detalles sobre cómo funciona, consulte el blog del creador de Redis, Salvatore, quien lo explica con gran detalle. Esencialmente, le permite mantener una forma eficiente de contar y fusionar elementos únicos en un conjunto sin tener que almacenar sus elementos. Un ejemplo simple de esto en acción:

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

API de exploración #

Redis v2.8 introdujo una nueva y hermosa operación SCAN que proporciona una estrategia óptima para atravesar un conjunto de claves completo de una instancia de redis en fragmentos de tamaño manejable utilizando solo un cursor del lado del cliente y sin introducir ningún estado del servidor. Es una alternativa de mayor rendimiento y debe usarse en lugar de KEYS en el código de la aplicación. SCAN y sus operaciones relacionadas para atravesar miembros de conjuntos, conjuntos ordenados y hashes ahora están disponibles en el cliente de Redis en las siguientes API:

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);
}

El IRedisClient proporciona una API de nivel superior que abstrae el cursor del cliente para exponer una secuencia Enumerable perezosa para proporcionar una forma óptima de transmitir resultados escaneados que se integra muy bien con LINQ, por ejemplo:

var scanUsers = Redis.ScanAllKeys("urn:User:*");
var sampleUsers = scanUsers.Take(10000).ToList(); //Stop after retrieving 10000 user keys