SlideShare uma empresa Scribd logo
1 de 26
Baixar para ler offline
Introdução ao Redis
Djeison A. Selzlein
Redis
- Redis = Remote Dictionary Service
- Armazém de estruturas de dados em memória
- NoSQL
- Chave-Valor
- Atomicidade de operações
Casos de Uso
- Cache
- Sessão (isolar estado)
- FPC (Full Page Caching)
- Filas
- Ranking e contabilização
- Ex.: usuários online, páginas acessadas, top 10
- Message broker (Pub/Sub)
Tipos de dados
- String
- Hash
- List
- Set
- Sorted set
- Bitmap
- Hyperloglog
- Geospatial Index
Plataformas
- Linux & MacOS:
- https://redis.io/download
- Windows
- Não possui versão oficial
- Versão experimental: https://github.com/MSOpenTech/redis
Executando
- Servidor
- redis-server
- :6379
- Cliente
- redis-cli
Strings - Get, Set & Del
- SET "key_name_string" "value_string"
- SET "key_name_number" 100
- GET "key_name_string"
- GET "key_name_string"
- DEL "key_name_string"
MGET & MSET
- MSET key value [key value ...]
- Ex.: MSET nome "Djeison" idade "23"
- MGET key [key ...]
- Ex.: MGET nome idade
Nomenclatura
- Padronizar para facilitar consultas
- Ex.:
- "resultado:megasena:01-06-2017"
- "spring:session:6F7741C417C33BE514C0DD5C11C09147"
Keys
- Consulta de chaves
- * = nenhum ou muitos caracteres
- ? = um caractere
- [] = define um domínio
- Ex.:
- KEYS *
- KEYS "spring:session:*"
- KEYS "megasena:resultado:??-05-2017"
- KEYS "megasena:resultado:1[49]-05-20??"
Hash - Hset, Hget & Hdel
- Contém pares de campo-valor
- HSET key field value
- Ex.: HSET "usuario:100" "nome" "Sidão"
- HGET key field
- Ex.: HGET "usuario:100" "nome"
- HDEL key field [field ...]
- Ex.: HDEL "usuario:100" "nome"
Expiração de chaves
- EXPIRE key seconds
- Tempo para expirar chave
- Ex.: EXPIRE "usuario:100" 60
- TTL key
- Tempo restante para expiração
- "-1" para nunca expira
- Ex.: TTL "usuario:100"
Incrementar e Decrementar
- INCR key
- Ex.: INCR valor_total
- DECR key
- INCRBY key increment
- Ex.: INCRBY valor_total 50
- DECRBY key decrement
- INCRBYFLOAT key increment
- Ex.: INCRBYFLOAT "temperatura" 2.5
- Ex.: INCRBYFLOAT "temperatura" -4.0
Bitmaps
- Conjunto de operações sobre bits
- SETBIT key offset value
- Ex.: SETBIT acesso:01-06-2017 30 1
- GETBIT key offset
- Ex.: GETBIT acesso:01-06-2017 30
- BITCOUNT key
- Ex.: BITCOUNT acesso:01-06-2017
Listas
- Implementação de Linked List
- LPUSH key value [value ...]
- RPUSH key value [value ...]
- "Empurra" valores para a lista
- Ex.: LPUSH mensagens "Esta é a primeira mensagem"
- LPOP key
- RPOP key
- "Consumir" valor da lista, remove elemento
- Ex.: LPOP mensagens
Listas
- LTRIM key start stop
- Aparar com base nos índices
- Ex.: LTRIM mensgens 0 5
- LINDEX key index
- Visualizar elemento
- Ex.: LINDEX mensagens 0
- LLEN key
- Obter tamanho
- Ex.: LLEN mensagens
- LRANGE key start stop
- Visualizar trecho específico
Espera ocupada (Busy Waiting)
- "É um técnica onde um processo checa de maneira repetitiva se
determinada condição é verdadeira" - Wikipedia
- Deve ser evitada pelo custo computacional
Pop blocante
- Aguarda caso fila esteja vazia
- BLPOP key [key ...] timeout
- BRPOP key [key ...] timeout
- Ex.: BLPOP mensagens 50
Conjuntos
- Não apresenta ordenação
- Não permite duplicidade
- Operações:
- Intersecção
- União
- Diferença
Conjuntos
- SADD key member [member ...]
- Ex.: SADD pessoas "Maria" "Joao" "Tadeu"
- SREM key member [member ...]
- Ex.: SREM pessoas "Joao" "Tadeu"
Conjuntos
- SCARD key
- Quantidade de elementos
- SMEMBERS key
- Elementos do conjunto
- SISMEMBER key member
- Identifica se membro está no conjunto
Conjuntos
- Intersecção:
- SINTER key [key ...]
- Ex.: SINTER pessoas familia
- Diferença
- SDIFF key [key ...]
- Ex.: SDIFF pessoas familia
- União
- SUNION key [key ...]
- Ex.: SUNION pessoas familia
Conjuntos Ordenados
- Valores únicos (Strings)
- Associa elemento a uma pontuação
- ZADD key score member
- Adiciona/Cria conjunto ordenado
- Ex.: ZADD jogadores 50 "Tulio"
- Ex.: ZADD jogadores 100 "Tulio"
- ZCARD key
- Cardinalidade do conjunto (número de elementos)
- Ex.: ZCARD jogadores
Conjuntos Ordenados
- ZRANGE key start stop [WITHSCORES]
- Elementos no "range" especificado em ordem crescente
- Ex.: ZRANGE jogadores 0 5 WITHSCORES
- ZREVRANGE key start stop [WITHSCORES]
- Decrescente
- Ex.: ZREVRANGE jogadores 0 -1
- -1 = último; -2 = penúltimo ...
Conjuntos Ordenados
- ZSCORE key member
- Ex.: ZSCORE jogadores joao
- ZRANK key member
- ZREVRANK key member
- Ex.: ZRANK jogadores rodolfo
Referências
https://redis.io/topics/introduction
http://objectrocket.com/blog/how-to/top-5-redis-use-cases
http://highscalability.com/blog/2011/7/6/11-common-web-use-cases-solved-in-redis.html
https://blog.butecopensource.org/redislite-redis-sem-necessidade-de-servidor-para-python/
https://en.wikipedia.org/wiki/Busy_waiting
https://cursos.alura.com.br/course/nosql-chave-valor-com-redis-1
https://cursos.alura.com.br/course/nosql-chave-valor-com-redis-2
http://docs.spring.io/spring-session/docs/1.3.1.RELEASE/reference/html5/

Mais conteúdo relacionado

Mais procurados

Google BigQuery Best Practices
Google BigQuery Best PracticesGoogle BigQuery Best Practices
Google BigQuery Best PracticesMatillion
 
Data Modeling with Neo4j
Data Modeling with Neo4jData Modeling with Neo4j
Data Modeling with Neo4jNeo4j
 
OrientDB - Time Series and Event Sequences - Codemotion Milan 2014
OrientDB - Time Series and Event Sequences - Codemotion Milan 2014OrientDB - Time Series and Event Sequences - Codemotion Milan 2014
OrientDB - Time Series and Event Sequences - Codemotion Milan 2014Luigi Dell'Aquila
 
JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0Mydbops
 
NOSQLEU - Graph Databases and Neo4j
NOSQLEU - Graph Databases and Neo4jNOSQLEU - Graph Databases and Neo4j
NOSQLEU - Graph Databases and Neo4jTobias Lindaaker
 
REDIS intro and how to use redis
REDIS intro and how to use redisREDIS intro and how to use redis
REDIS intro and how to use redisKris Jeong
 
RDBMS to Graph
RDBMS to GraphRDBMS to Graph
RDBMS to GraphNeo4j
 
Intro to Graphs and Neo4j
Intro to Graphs and Neo4jIntro to Graphs and Neo4j
Intro to Graphs and Neo4jjexp
 
Core Concepts in azure data factory
Core Concepts in azure data factoryCore Concepts in azure data factory
Core Concepts in azure data factoryBRIJESH KUMAR
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationrjsmelo
 
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLTop 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLJim Mlodgenski
 
MySQL_MariaDB로의_전환_기술요소-202212.pptx
MySQL_MariaDB로의_전환_기술요소-202212.pptxMySQL_MariaDB로의_전환_기술요소-202212.pptx
MySQL_MariaDB로의_전환_기술요소-202212.pptxNeoClova
 
Simplifying Change Data Capture using Databricks Delta
Simplifying Change Data Capture using Databricks DeltaSimplifying Change Data Capture using Databricks Delta
Simplifying Change Data Capture using Databricks DeltaDatabricks
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index CookbookMYXPLAIN
 
ClickHouse Introduction by Alexander Zaitsev, Altinity CTO
ClickHouse Introduction by Alexander Zaitsev, Altinity CTOClickHouse Introduction by Alexander Zaitsev, Altinity CTO
ClickHouse Introduction by Alexander Zaitsev, Altinity CTOAltinity Ltd
 
Using ClickHouse for Experimentation
Using ClickHouse for ExperimentationUsing ClickHouse for Experimentation
Using ClickHouse for ExperimentationGleb Kanterov
 
JanusGraph DataBase Concepts
JanusGraph DataBase ConceptsJanusGraph DataBase Concepts
JanusGraph DataBase ConceptsSanil Bagzai
 
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재PgDay.Seoul
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBMydbops
 

Mais procurados (20)

Google BigQuery Best Practices
Google BigQuery Best PracticesGoogle BigQuery Best Practices
Google BigQuery Best Practices
 
Data Modeling with Neo4j
Data Modeling with Neo4jData Modeling with Neo4j
Data Modeling with Neo4j
 
OrientDB - Time Series and Event Sequences - Codemotion Milan 2014
OrientDB - Time Series and Event Sequences - Codemotion Milan 2014OrientDB - Time Series and Event Sequences - Codemotion Milan 2014
OrientDB - Time Series and Event Sequences - Codemotion Milan 2014
 
JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0
 
NOSQLEU - Graph Databases and Neo4j
NOSQLEU - Graph Databases and Neo4jNOSQLEU - Graph Databases and Neo4j
NOSQLEU - Graph Databases and Neo4j
 
REDIS intro and how to use redis
REDIS intro and how to use redisREDIS intro and how to use redis
REDIS intro and how to use redis
 
RDBMS to Graph
RDBMS to GraphRDBMS to Graph
RDBMS to Graph
 
Intro to Graphs and Neo4j
Intro to Graphs and Neo4jIntro to Graphs and Neo4j
Intro to Graphs and Neo4j
 
Core Concepts in azure data factory
Core Concepts in azure data factoryCore Concepts in azure data factory
Core Concepts in azure data factory
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
 
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLTop 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
 
MySQL_MariaDB로의_전환_기술요소-202212.pptx
MySQL_MariaDB로의_전환_기술요소-202212.pptxMySQL_MariaDB로의_전환_기술요소-202212.pptx
MySQL_MariaDB로의_전환_기술요소-202212.pptx
 
Simplifying Change Data Capture using Databricks Delta
Simplifying Change Data Capture using Databricks DeltaSimplifying Change Data Capture using Databricks Delta
Simplifying Change Data Capture using Databricks Delta
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 
ClickHouse Introduction by Alexander Zaitsev, Altinity CTO
ClickHouse Introduction by Alexander Zaitsev, Altinity CTOClickHouse Introduction by Alexander Zaitsev, Altinity CTO
ClickHouse Introduction by Alexander Zaitsev, Altinity CTO
 
Using ClickHouse for Experimentation
Using ClickHouse for ExperimentationUsing ClickHouse for Experimentation
Using ClickHouse for Experimentation
 
JanusGraph DataBase Concepts
JanusGraph DataBase ConceptsJanusGraph DataBase Concepts
JanusGraph DataBase Concepts
 
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
 
Log Structured Merge Tree
Log Structured Merge TreeLog Structured Merge Tree
Log Structured Merge Tree
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDB
 

Semelhante a Introdução ao Redis

Fluentd/LogStash + elastic search + kibana
Fluentd/LogStash + elastic search + kibanaFluentd/LogStash + elastic search + kibana
Fluentd/LogStash + elastic search + kibanaCésar Araújo
 
Comandos básicos em linux
Comandos básicos em linuxComandos básicos em linux
Comandos básicos em linuxRogerio Pereira
 
pgBouncer: um aglomerador de conexões para PostgreSQL
pgBouncer: um aglomerador de conexões para PostgreSQLpgBouncer: um aglomerador de conexões para PostgreSQL
pgBouncer: um aglomerador de conexões para PostgreSQLelliando dias
 
Redis um banco chave valor
Redis um banco chave valorRedis um banco chave valor
Redis um banco chave valorKinn Julião
 
Introdução ao MongoDB II
Introdução ao MongoDB IIIntrodução ao MongoDB II
Introdução ao MongoDB IILuiz Duarte
 
Palestra python
Palestra pythonPalestra python
Palestra pythonRony Cruch
 
SAPO Broker
SAPO BrokerSAPO Broker
SAPO Brokercodebits
 
Palestra DataFlow - II São Paulo Perl Workshop
Palestra DataFlow - II São Paulo Perl WorkshopPalestra DataFlow - II São Paulo Perl Workshop
Palestra DataFlow - II São Paulo Perl WorkshopAlexei Znamensky
 
Lidando com Código Duplicado - PHP Conference Brasil 2013
Lidando com Código Duplicado - PHP Conference Brasil 2013Lidando com Código Duplicado - PHP Conference Brasil 2013
Lidando com Código Duplicado - PHP Conference Brasil 2013Evaldo Junior
 
Zabbix monitorando o zimbra collaboration 8.8 (1)
Zabbix   monitorando o zimbra collaboration 8.8 (1)Zabbix   monitorando o zimbra collaboration 8.8 (1)
Zabbix monitorando o zimbra collaboration 8.8 (1)PAULO R. DEOLINDO JUNIOR
 

Semelhante a Introdução ao Redis (13)

Fluentd/LogStash + elastic search + kibana
Fluentd/LogStash + elastic search + kibanaFluentd/LogStash + elastic search + kibana
Fluentd/LogStash + elastic search + kibana
 
Palestra cbq
Palestra cbqPalestra cbq
Palestra cbq
 
Redis
RedisRedis
Redis
 
Comandos básicos em linux
Comandos básicos em linuxComandos básicos em linux
Comandos básicos em linux
 
pgBouncer: um aglomerador de conexões para PostgreSQL
pgBouncer: um aglomerador de conexões para PostgreSQLpgBouncer: um aglomerador de conexões para PostgreSQL
pgBouncer: um aglomerador de conexões para PostgreSQL
 
Redis um banco chave valor
Redis um banco chave valorRedis um banco chave valor
Redis um banco chave valor
 
Introdução ao MongoDB II
Introdução ao MongoDB IIIntrodução ao MongoDB II
Introdução ao MongoDB II
 
Palestra python
Palestra pythonPalestra python
Palestra python
 
SAPO Broker
SAPO BrokerSAPO Broker
SAPO Broker
 
Palestra DataFlow - II São Paulo Perl Workshop
Palestra DataFlow - II São Paulo Perl WorkshopPalestra DataFlow - II São Paulo Perl Workshop
Palestra DataFlow - II São Paulo Perl Workshop
 
PHP e Redis
PHP e RedisPHP e Redis
PHP e Redis
 
Lidando com Código Duplicado - PHP Conference Brasil 2013
Lidando com Código Duplicado - PHP Conference Brasil 2013Lidando com Código Duplicado - PHP Conference Brasil 2013
Lidando com Código Duplicado - PHP Conference Brasil 2013
 
Zabbix monitorando o zimbra collaboration 8.8 (1)
Zabbix   monitorando o zimbra collaboration 8.8 (1)Zabbix   monitorando o zimbra collaboration 8.8 (1)
Zabbix monitorando o zimbra collaboration 8.8 (1)
 

Introdução ao Redis