desenvolvendo serviços de alta performance com apis nosql para mysql
DESCRIPTION
As exigências cada vez maiores de performance nas aplicações Web têm gerado grande demanda para novos métodos de acesso NoSQL para MySQL. Tais métodos foram implementados recentemente e incluem APIs Java e Memcached que são uma alternativa de alto desempenho para consultas simples e que não requerem a definição de um esquema de dados rígido, mas também permitem aproveitar todas as vantagens já conhecidas de bancos de dados relacionais existentes. Esta apresentação descreve os novos métodos de acesso NoSQL para MySQL Server com InnoDB e MySQL Cluster e alguns casos de uso em arquiteturas Web.TRANSCRIPT
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 1
Airton Lastori [email protected]
out-2012
Desenvolvendo Serviços de Alta Performance com APIs NoSQL para MySQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 2
Alguns clientes MySQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 3
Alguns clientes MySQL
fonte: alexa.com/topsites 10-mai-2012
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 4
Agenda
Alta Performance com MySQL
Arquitetura e Topologias
Métodos de Acesso e API’s
Instalação e Exemplos
Aprenda Mais
Perguntas?
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 5
Agenda
Alta Performance com MySQL
Arquitetura e Topologias
Métodos de Acesso e API’s
Instalação e Exemplos
Aprenda Mais
Perguntas?
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 6
Alta Performance Por que há demanda?
Velocidade de escrita
Acesso chave/valor
Modelo de dados flexível
Escalabilidade horizontal
Suporte à “Big Data”
Disponível 24x7 5,9 BILHÕES ASSINATURAS
MÓVEIS EM 2011
1,2+ BILHÃO APPS iOS & Android JÁ AIXADOS EM 2012
$1 TRILHÃO EM 2013
$700 BILHÕES EM 2011
2.2 BILHÕES DE USUÁRIOS
630 MILHÕES DE WEBSITES
400 MILHÕES
DE TWEETS POR DIA
1 BILHÃO USUÁRIOS
560 MILHÕES ATIVOS DIARIAMENTE
72 HORAS UPLOAD A CADA
MINUTO
40% CRESCIMENTO
DE DADOS POR ANO
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 7
Resposta tecnológica: NoSQL
Fonte: 451 Group
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 8
Resposta tecnológica: NoSQL
Usos comuns: usado como cache para
armazenamento de dados requisitados
frequentemente, especialmente em
aplicações web.
Pontos Fortes: escalabilidade,
armazenamento e busca de dados muito
rápidos; dados não estruturados e
parcialmente estruturados.
Pontos Fracos: usualmente todos os dados
tem que caber em memória rápida; falta de
recursos para Queries complexas.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 9
Uso Tradicional do Memcached 2 níveis de hashing
Memcache
httpd memcached
memcached
memcached chave memcache
PHP/Perl/Java
friends:12389
Usa chave
para
encontrar o
dado (valor)
VALUE friends:12389 0 31\r\n 101, 11009, 11150, 55881, 77798 \r\n
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 10
Não encontra valor no cache: sincronização 1/2 aplicação é responsável por buscar no Banco de Dados
Memcache
httpd memcached
memcached
memcached
PHP/Perl/Java Não há valor
para chave
informada
MySQL
Slave
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 11
Não encontra valor no cache: sincronização 2/2 aplicação é responsável por sincronizar
Memcache
httpd memcached
memcached
memcached
PHP/Perl/Java
Armazenar
valor com
chave/valor
informados
Processo similar ocorre quando há escrita
no MySQL Master: aplicação precisa
sincronizar com cache.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 12
Memcached com
Persistência no InnoDB Método transparente para persistir
os dados em memória volátil
Memcached plug-in no mysqld ,
mapeado à API nativa do InnoDB
Shared process para baixa latência
Acesso chave-valor ao
InnoDB Via Memcached API
Usa clients Memcached existentes
Sem SQL parsing
Acesso SQL e NotOnlySQL Operações chave-valor mas
também queries SQL, JOINs, FKs,
etc.
SQL (MySQL Client)
InnoDB Storage Engine
MySQL Server Memcached plugin
Application
NoSQL (Memcached Prot.)
mysqld
Memcached + InnoDB MySQL 5.6
Mais Flexibilidade e Simplicidade
http://dev.mysql.com/doc/refman/5.6/en/innodb-memcached.html
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 13
Resposta tecnológica: NoSQL
Usos comuns: aplicações web ou
outras que requerem melhor
performance e escalabilidade sem que
seja necessários definir esquemas
relacionais.
Pontos Fortes: armazenamento
persistente com recursos de
escalabilidade tais como sharding
nativo; melhor suporte a Queries que
apenas chave-valor.
Pontos Fracos: falta de recursos para
Queries complexas.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 14
Resposta tecnológica: NoSQL
Usos comuns: aplicações
científicas ou de tradução direta do
paradigma orientado a objetos.
Pontos Fortes: performance e
mapeamento natural de objetos.
Pontos Fracos: falta de recursos
para realizar Queries complexas.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 15
Resposta tecnológica: NoSQL
Usos comuns: log em tempo-real para
aplicações web ou financeiras.
Pontos Fortes: throughput muito alto
para Big Data (de Terabytes a
Petabytes); suporte excelente a
particionamento e acesso aleatório de
leitura-escrita.
Pontos Fracos: APIs de baixo-nível,
falta de recursos para realizar Queries
complexas, alta latência na resposta de
Queries.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 16
Requisitos NoSQL O que a solução deve cumprir?
Alta Performance alto throughput leitura/escrita
Escalabilidade massiva auto-sharding
Facilidade de uso acesso simples (APIs)
manutenção simples
modelo evolutivo de dados
Alta Disponibilidade tolerância a falhas
Performance
Escalabilidade
Facilidade de Uso
Disponibilidade ~24x7
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 17
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 18
Ainda há espaço para SGBDs relacionais
Usos comuns: análise de dados
históricos, data warehousing,
business intelligence.
Pontos Fortes: suporte a Queries
rápidas especialmente em datasets
grandes e compressão.
Pontos Fracos: não adequado
para transações, importações e
exportações rápidas; utilização de
computação pesada.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 19
Ainda há espaço para SGBDs relacionais
Usos comuns: processamento de
transações, aplicações interativas
transacionais
Pontos Fortes: formas facilitadas de
manipular registros; consistência;
tecnologia comprovadamente robusta.
Pontos Fracos: problemas de
escalabilidade, especialmente para
Queries contra grande volume de
dados (dezenas de Terabytes).
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 20
Scale Out
• Adicionar mais servidores para
aumentar performance
• MySQL adota esta abordagem
em sistemas altamente
escaláveis em hardware
commodity (Intel / AMD)
Scale Up
• Trocar por hardware mais
poderoso, adicionar memória,
CPU
• Outras soluções normalmente
usam hardware proprietário
(SMP)
Escalabilidade: horizontal vs vertical
É possível combinar as duas abordagens
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 23
MySQL 5.5.28
MySQL 5.6.7
MySQL 5.6 SysBench Benchmarks
151% Ganho Performance
0
2.000
4.000
6.000
8.000
10.000
12.000
32 64 128 256 512
Tra
ns
ac
tio
ns
pe
r S
ec
on
d
Connections
MySQL 5.6 vs. 5.5 - Read Write (Linux)
Oracle Linux 6
Intel(R) Xeon(R) E7540 x86_64
MySQL leveraging:
- 48 of 96 available CPU threads
- 2 GHz, 512GB RAM
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 24
MySQL 5.5.28
MySQL 5.6.7
MySQL 5.6 SysBench Benchmarks
234% Ganho de Performance
0
2.000
4.000
6.000
8.000
10.000
12.000
14.000
16.000
18.000
32 64 128 256 512
Tra
ns
ac
tio
ns
pe
r S
ec
on
d
Connections
MySQL 5.6 vs. 5.5 - Read Only (Linux)
Oracle Linux 6
Intel(R) Xeon(R) E7540 x86_64
MySQL leveraging:
- 48 of 96 available CPU threads
- 2 GHz, 512GB RAM
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 25
MySQL Enterprise Edition ComThread Pool
MySQL Community Server SemThread Pool
3x Melhor Escalabilidade com Thread Pool
MySQL 5.5.16
Oracle Linux 6.1, Unbreakable Kernel 2.6.32
2 sockets, 24 cores, 2 X 12-core
Intel(R) Xeon(R) X5670 2.93GHz CPUs
72GB DDR3 RAM
2 X LSI SCSI Disk (MR9261-8i) (597GB)
0
2.000
4.000
6.000
8.000
10.000
12.000
T
Conexões Simultâneas no Banco de Dados
MySQL 5.5 Sysbench OLTP Apenas Leitura
Comparativo com/sem Thread Pool
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 26
MySQL Enterprise Edition ComThread Pool
MySQL Community Server Sem Thread Pool
Comparativo com/sem Thread Pool
20x Melhor Escalabilidade comThread Pool
0
1.000
2.000
3.000
4.000
5.000
6.000
7.000
8.000
Tra
ns
aç
õe
s p
or
se
gu
nd
o
Conexões Simultâneas no Banco de Dados
MySQL 5.5 Sysbench OLTP Leitura/Escrita
MySQL 5.5.16
Oracle Linux 6.1, Unbreakable Kernel 2.6.32
2 sockets, 24 cores, 2 X 12-core
Intel(R) Xeon(R) X5670 2.93GHz CPUs
72GB DDR3 RAM
2 X LSI SCSI Disk (MR9261-8i) (597GB)
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 27
Escalabilidade horizontal
Replicação MySQL
Particionamento Funcional
Data Sharding
3 Abordagens para
escalar o MySQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 28
Escalabilidade horizontal
• método mais simples e mais comum
• indicado para aplicações de LEITURA intensiva
• problemas com cache duplicado em aplicações com datasets grandes
Replicação MySQL
• dividir a carga em múltiplos nós, com responsabilidades distintas
• os nós podem ter redundância via replicação para alta-disponibilidade
• normalmente não é transparente para a aplicação e também recorre ao scale up para cada database funcional, o que impõe limites
Particionamento Funcional
• método de maior sucesso para escalar aplicações MySQL de grande porte hoje
• dados compartilhados em tabelas/caches globais, SOA
• difícil de adaptar aplicações legadas
Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 29
Aplicação
Replicação MySQL: como escalar 1/2
Master Slave
• Divisão de leituras e escritas (R/W Split)
• Modelo assíncrono (padrão)
• Modelo semi-síncrono (a partir da versão 5.5)
Escritas & Leituras Leituras
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 30
Replicação MySQL: como escalar 2/2
Leituras Leituras
• Escreva para 1 Master
• Leia de vários Slaves, adicione mais quando necessário
• Perfeito para aplicações de leitura intensiva
Aplicação
Replicação MySQL
Load Balancer
Master Slave Slave
Escritas & Leituras
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 31
Benefício-chave
• O MySQL permite economias
significativas com custos de
hardware, adicionando novos
servidores commodity de
acordo com o necessário e de
maneira incremental
Por que MySQL? • Capacidade de escalar
conforme necessidade e de
maneira incremental
• Baixos custos e flexibilidade
Wikipedia
mysql.com/customers
Caso de sucesso
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 32
Escalabilidade horizontal
• método mais simples e mais comum
• indicado para aplicações de LEITURA intensiva
• problemas com cache duplicado em aplicações com datasets grandes
Replicação MySQL
• dividir a carga em múltiplos nós, com responsabilidades distintas
• os nós podem ter redundância via replicação para alta-disponibilidade
• normalmente não é transparente para a aplicação e também recorre ao scale up para cada database funcional, o que impõe limites
Particionamento Funcional
• método de maior sucesso para escalar aplicações MySQL de grande porte hoje
• dados compartilhados em tabelas/caches globais, SOA
• difícil de adaptar aplicações legadas
Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 33
Data Node 1
Data Node 2
Data Node 3
Data Node 4
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 34
Data Node 1
Data Node 2
F1
Data Node 3
Data Node 4
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 35
Data Node 1
Data Node 2
F1
F1
Data Node 3
Data Node 4
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 36
Data Node 1
Data Node 2
F1
F3 F1
Data Node 3
Data Node 4
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 37
Data Node 1
Data Node 2
F1 F3
F3 F1
Data Node 3
Data Node 4
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 38
Data Node 1
Data Node 2
F1 F3
F3 F1
Data Node 3
Data Node 4
F2
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 39
Data Node 1
Data Node 2
F1 F3
F3 F1
Data Node 3
Data Node 4
F2
F2
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 40
Data Node 1
Data Node 2
F1 F3
F3 F1
Data Node 3
Data Node 4
F2
F4 F2
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 41
Data Node 1
Data Node 2
F1 F3
F3 F1
Data Node 3
Data Node 4
F2 F4
F4 F2
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 42
Data Node 1
Data Node 2
F3
F1
Data Node 3
Data Node 4
F2 F4
F4 F2
Node Group 1
Table T1
P2
P3
P4
P1
F1
F3
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 43
Data Node 1
Data Node 2
F1 F3
F3 F1
Data Node 3
Data Node 4
F2 F4
F4 F2
Node Group 1
Node Group 2
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 44
Data Node 1
Data Node 2
F1 F3
F3 F1
Data Node 3
Data Node 4
F2 F4
F4 F2
Node Group 1
Node Group 2
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 45
Data Node 1
Data Node 2
F1 F3
F3 F1
Data Node 3
Data Node 4
F2 F4
F4 F2
Node Group 1
Node Group 2
Table T1
P2
P3
P4
P1
Escalabilidade horizontal: Data Sharding
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 46
Benefícios-chave
• Propriedades ACID
• Solução comprovada por muitas
empresas ao longo de anos
• Por que MySQL? • Escalabilidade virtualmente infinita:
hoje com 20 milhões de usuários, 1
bilhão de Notes e 2 bilhões de
arquivos (fotos, documentos etc)
• Flexibilidade para crescer de
maneira incremental e com baixos
custos
Caso de sucesso
Evernote
blog.evernote.com/tech/2012/02/23/whysql
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 47
NewSQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 48
Requisitos NewSQL Relacional + NoSQL
Não há solução única para
todas situações. Não há
bala de prata.
Combine e supere
expectativas!
Performance
Escalabilidade
Facilidade de Uso
Disponibilidade ~24x7
SQL/Joins
Transações ACID
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 49
MySQL Cluster
• Arquitetura shared-nothing in-memory parallel
• Modelo relacional ACID, SQL
Carrier Grade Database
• 99.999% de disponibilidade
• Self-healing, failover abaixo de 1 segundo Alta Disponibilidade
• Performance em tempo real para altas cargas
• Latência baixa e preditiva Alta Performance
• Elasticidade, crescimento incremental
• Escalabilidade linear, distribuition aware Escalabilidade
• Open Source, hardware commodity
• APIs NoSQL (C++, Java, Memcached, Node.js) Open Source
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 50
Alguns Clientes MySQL Cluster
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 51
•2 milhões usuários, com 30.000 novos
usuários por dia
•10.000 usuários concorrentes
•10.000 Transações Por Segundo
•99.999% uptime
“The MySQL support service has
been essential in helping us for
troubleshooting and giving
recommendations for the production
cluster.” Carlos Morales (DBA), Playfulplay.com
blogs.oracle.com/MySQL/entry/mysql_cluster_powers_el_chavo
Caso de sucesso
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 52
Performance do MySQL Cluster
8 Servidores Intel Commodity
– 2 x 6-core processors 2.93GHz
– x5670 processors (24 threads)
– 48GB RAM
Rede Infiniband
flexAsynch benchmark (NDB API)
0
200
400
600
800
1.000
1.200
2 4 8
Mil
lio
ns
Number of Data Nodes
SELECT Queries per Minute
0
50
100
150
4 8
Mil
lio
ns
Number of Data Nodes
UPDATE Queries per Minute
Performance a
Escalabilidade
Facilidade de Uso
Disponibilidade ~24x7
SQL/Joins
Transações ACID
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 53
Agenda
Alta Performance com MySQL
Arquitetura e Topologias
Métodos de Acesso e API’s
Instalação e Exemplos
Aprenda Mais
Perguntas?
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 54
MySQL Cluster Data Nodes
Data Layer
Clients
Management
Arquitetura MySQL Cluster Performance a
Escalabilidade
Facilidade de Uso ?
Disponibilidade ~24x7
SQL/Joins ?
Transações ACID ? Application Layer
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 55
MySQL Cluster Data Nodes
Data Layer
Clients
Application Layer
Management
Arquitetura MySQL Cluster Performance a
Escalabilidade
Facilidade de Uso a
Disponibilidade ~24x7
SQL/Joins a
Transações ACID a
NDB
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 56
MySQL Cluster Data Nodes
Data Layer
Clients
Application Layer
Management
Arquitetura MySQL Cluster Performance a
Escalabilidade ?
Facilidade de Uso a
Disponibilidade ~24x7
SQL/Joins a
Transações ACID a
Table T1
P2
P3
P4
P1 P1
P3
P2
P4
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 57
MySQL Cluster Data Nodes
Data Layer
Clients
Application Layer
Management
Arquitetura MySQL Cluster Performance a
Escalabilidade a
Facilidade de Uso a
Disponibilidade ~24x7 ?
SQL/Joins a
Transações ACID a
P1
P3
P2
P4 Management
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 58
MySQL Cluster Data Nodes
Data Layer
Clients
Application Layer
Management
Arquitetura MySQL Cluster Performance a
Escalabilidade a
Facilidade de Uso a
Disponibilidade ~24x7 a
SQL/Joins a
Transações ACID a
P1
P3
P2
P4
Management
P3
P1
P4
P2
E mais:
• Permite mudanças no
schema sem interrupção de
leituras ou escritas
• Permite adicionar colunas
e índices online
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 59
Cluster 1
Synchronous
replication
Cluster 2
InnoDB InnoDB InnoDB
Asynchronous
replication
Flexibilidade da Topologia Replicação
Replicação síncrona entre os grupos de nós para HA
Geo-Replicação assíncrona entre nós remotos
NDB para redundância
geográfica
Replicação assíncrona entre Storage Engines
diferentes para aplicações
especializadas como geração
de relatórios
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 60
Agenda
Alta Performance com MySQL
Arquitetura e Topologias
Métodos de Acesso e API’s
Instalação e Exemplos
Aprenda Mais
Perguntas?
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 61
Os mesmos dados
acessados
simultaneamente
através de interfaces
SQL e NoSQL
APIs de Acesso aos Dados
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 62
APIs Java: ClusterJ e JPA
ClusterJ API de persistência Domain
Object Model (DataMapper)
JPA API de persistência padronizada
pelo OpenJPA
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 63
ClusterJ ou JPA?
ClusterJ Fácil de usar, parecida com Hibernate /
JPA / JDO
– Domain Object Model DataMapper pattern
– Dados são representados por Objetos de Domínio
– Objetos de Domínio não contém lógica de negócio (camada
separada)
– Objetos de Domínio são mapeados para tabelas no MySQL
Altíssima Performance
Construído sobre interface nativa Java
– JNI adapter (ndbjtie)
– Parte integral do MySQL Cluster
– Mapeamento direto do MySQL Cluster API (NDB API) para
Java
Limitação: não suporta relacionamentos
– Olhe na API JPA / JDO para estes padrões de modelagem
JPA A interface JPA interface é compatível
com o padrão Java Persistent API
– Implementada como um plugin OpenJPA
Performance mais alta que o JDBC puro
Construída sobre ClusterJ e JDBC
– Usa ClusterJ onde possível e reverte para JDBC para
algumas operações
Adoção mais natural para profissionais
Java
Facilita adoção do Cluster em aplicações
web e aplicações legadas
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 64
API Memcached Baseado em chave-valor
API simples e bastante popular entre
desenvolvedores
hash table com persistência em disco
e alta performance
Extensão do Memcached adiciona persistência em disco sem
perda de performance
evita rotinas de invalidação do cache,
sincronismo manual
Simplicidade e Flexibilidade evita camadas adicionais na infra-
estrutura
acesso ao dado via tabelas relacionais
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 65
Evolução rápida da
aplicação:
Novos tipos de dados
adicionados
constantemente
Não requer tempo para
estender o schema ou
parada do servidor
Não requer conhecimento
de modelagem relacional
Escalabilidade incremental
Memcached é Schemaless
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 66
<town:maidenhead,SL6>
key value
<town:maidenhead,SL6>
key value
Key Value
town:maidenhead SL6
generic table
Application view
SQL view
Cluster & Memcached Schemaless
set maidenhead 0 0 3
SL6
STORED
get maidenhead
VALUE maidenhead 0 3
SL6
END
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 67
<town:maidenhead,SL6>
prefix key value
<town:maidenhead,SL6>
key value
Prefix Table Key-
col
Val-col policy
town: map.zip town code cluster
Config tables
town ... code ...
maidenhead ... SL6 ...
map.zip
Application view
SQL view
Cluster & Memcached Schema configurável
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 68
Flexibilidade da Topologia API Memcached
• Várias opções de implantação
• Múltiplos Clusters
• Pode manter Memcached server, se preferir
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 69
Node.js NoSQL API MySQL Cluster 7.3 EA Acesso JavaScript nativo ao
MySQL Cluster
JavaScript do início ao fim: browser >
app > database
Leituras e escritas de objetos JavaScript
direto no MySQL Cluster
Elimina transformações SQL
Implementado como um módulo
para node.js
Integra completamente a API/library
Cluster com a aplicação web
Alta performance para aplicações e
dados distribuídos
V8 JavaScript Engine
MySQL Cluster Node.js Module
MySQL Cluster Data Nodes
Clients
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 70
Qual API devo usar?
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 71
Agenda
Alta Performance com MySQL
Arquitetura e Topologias
Métodos de Acesso e API’s
Instalação e Exemplos
Aprenda Mais
Perguntas?
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 72
Auto-Installer MySQL Cluster 7.3 EA
Rápida configuração
Auto-discovery
Otimização de acordo com a
carga prevista
Melhores práticas de
implantação
MySQL Cluster 7.2 e 7.3
Especifique a carga
Auto-Discover
Defina a Topologia Deploy
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 73
MySQL Cluster Auto-Install (beta)
Simples de instalar e provisionar clusters multi-node
Complementa MySQL Cluster Manager no gerenciamento de cliclo de vida
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 74
1. Download MCM/Cluster package: edelivery.oracle.com:
2. Unzip
3. Execute o agent, defina, crie & inicialize o Cluster!
$> bin\mcmd –bootstrap MySQL Cluster Manager 1.1.2 started
Connect to MySQL Cluster Manager by running "D:\Andrew\Documents\MySQL\mcm\bin\mcm" -a NOVA:1862
Configuring default cluster 'mycluster'...
Starting default cluster 'mycluster'...
Cluster 'mycluster' started successfully
ndb_mgmd NOVA:1186
ndbd NOVA
ndbd NOVA
mysqld NOVA:3306
mysqld NOVA:3307
ndbapi *
Connect to the database by running "D:\Andrew\Documents\MySQL\mcm\cluster\bin\mysql" -h NOVA -P 3306 -u root
MySQL Cluster Manager Para testes em uma única máquina
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 75
ClusterJ: como usar
• Defina Table para Java Mapping
• Defina Connection para o Cluster
• Crie Session
• Comandos: Create, Update, Delete, Find by primary
key
• Query (SELECT)
• O que achou da PERFORMANCE?
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 76
ClusterJ Gera Classes @PersistenceCapable(table="employee")
public interface Employee {
long getId();
void setId(int id);
@Column(name="full_name")
String getName();
void setName(String value);
int getSalary();
void setSalary(int value);
Integer getAge();
void setAge(Integer value);
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 77
ClusterJ Base Class public class Employee
extends DynamicObject {
public String table() {
return "employee";
long getId() {
return (Long)get(0);
}
void setId(long value) {
set(0, value);
}
...
// other fields and behavior
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 78
Exemplo: ClusterJ 1/3 Session session;
void getSession() {
session = sessionFactory.getSession();
}
Employee createEmployee(long id, String name,
int salary, int age) {
Employee employee =
session.newInstance(Employee.class);
employee.setId(id);
employee.setName(name);
employee.setSalary(salary);
employee.setAge(age);
session.persist(employee);
return employee;
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 79
Exemplo: ClusterJ 2/3
Employee findEmployee(long id) {
Employee employee =
session.find(Employee.class, id);
return employee;
}
void updateSalary(long id, int salary) {
Employee employee = findEmployee(id);
employee.setSalary(salary);
session.updatePersistent(employee);
}
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 80
Exemplo: ClusterJ 3/3 Query
QueryDomainType qemp =
builder.createQueryDefinition(Employee.class) ;
Predicate geAge = qemp.get("age")
.greaterEqual(qemp.param("ageFloor"));
Predicate leSalary = qemp.get("salary")
.lessEqual(qemp.param("salaryCap"));
qemp.where(geAge.and(leSalary));
Query query = session.createQuery(qemp) ;
query.setOrdering(Query.DESCENDING, "age");
query.setParameter("ageFloor",33);
query.setParameter("salaryCap", 44000);
List<Employee> results = query.getResultList() ;
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 81
Mais Exemplos ClusterJ e ClusterJPA
Whitepaper:
MySQL Cluster Connector for Java
April 2010
mysql.com/why-mysql/white-papers
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 82
Exemplos Memcached API
Ondemand Webinar:
NoSQL Memcached API for MySQL Cluster
22 August 2012
mysql.com/news-and-events/on-demand-webinars/display-od-723.html
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 83
Exemplos JavaScript / Node.js API
Blog:
Tutorial Getting Started with the NoSQL JavaScript / Node.js API for
MySQL Cluster
10 June 2012
blogs.oracle.com/MySQL/entry/tutorial_getting_started_with_the
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 84
Agenda
Alta Performance com MySQL
Arquitetura e Topologias
Métodos de Acesso e API’s
Instalação e Exemplos
Aprenda Mais
Perguntas?
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 85
Mais sobre como começar com MySQL Cluster
Whitepaper:
MySQL Cluster Evaluation Guide
February 2012
mysql.com/why-mysql/white-papers
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 86
Comece hoje
Learn More
Evaluate MySQL Cluster 7.3 Auto-Install a Cluster
Developer Zone dev.mysql.com
Download Today dev.mysql.com/download
s/cluster/
labs.mysql.com
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 87
Sumário
As aplicações Web demandam mais dos bancos de dados
nos dias de hoje.
São exigidos mais performance, escalabilidade horizontal,
APIs e padões de acesso simples e poderosos.
O MySQL cumpre estes requisitos e ainda mantém os
benefícios de um SGBD relacional.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 88
Perguntas?
Desenvolvendo Serviços de Alta Performance com APIs NoSQL para MySQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 89
@MySQLBR
meetup.com/MySQL-BR
facebook.com/MySQLBR
Obrigado!