SlideShare a Scribd company logo
1 of 48
HandlerSocketилиУскоряем MySQLв десятки раз Александр Календарев
План Кратко об HandlerSoket HandlerSoket изнутри Инсталляция HandlerSoket Протокол Использование HandlerSoket
Что может дать ускорение Отсутствиеразбора SQL запроса Выполнение несколько операций в одном запросе Снижение сетевого трафика за счет протокола
Интерфейс  Handler HANDLER tbl_name OPEN [ [AS] alias] HANDLER tbl_name READ index_name { = | <= | >= | < | > } (value1,value2,...) [ WHERE where_condition ] [LIMIT ... ] HANDLER tbl_name CLOSE
HandlerSoket Плагин к MySQL Предоставляет NoSQLинтерфейс  к таблицам данных MySQL Автор: Akira Higuchi
Возможности Представляет доступ к данным по индексу Операциис данными: = < и > Top и  Limit
Где Плагин к MySQL5.2.5 https://github.com/ahiguti/HandlerSocket-Plugin-for-MySQL PerconaServer 5.1 http://www.percona.com/downloads/Percona-Server-5.1/LATEST/
Applications Libmysql libhsclient Listener for libmysql SQL Layer Handlersocket Plugin Handler Interface InnoDb MyISAM Other storage engines … Структура HandlerSocket client app mysqld
Сетевое взаимодействие
Потоковая модель Небольшое кол-во потоков Несколько коннекций на один поток epollмодель Небольшое потребление  памяти на один поток
Структура читающего потока reads requests from many clients locks the DB, gets a read view locks/unlocks (1/#conns) executes many requests unlocks the DB returns responses to clients
Структура пишущего потока reads requests from many clients Locks DB, begins a transaction locks/unlocks (1/#conns) executes many requests commits, and unlocks the DB returns responses to clients
Инсталляция ./configure 	--with-mysql-source=... 	--with-mysql-bindir=...   --with-mysql-plugindir=...
Инсталляция ./mysql_config --variable=pkglibdir  /usr/local/mysql/lib mysql_config --plugindir /usr/local/mysql/lib/plugin --with-mysql-bindir  --with-mysql-plugindir
Инсталляция $ make   $ sudo make install $ vi my.conf
Инсталляция [mysqld]  # the port number to bind to (and for write) loose_handlersocket_port = 9998 loose_handlersocket_port_wr = 9999  # the number of worker threads  loose_handlersocket_threads = 16 loose_handlersocket_threads_wr = 1 #to allow handlersocket accept connections open_files_limit = 65535
Инсталляция mysql> install plugin handlersocket soname 'handlersocket.so';
Проверка:show processlist  mode=rd  mode=wr
Проверка:show processlist 5 conns, 0 active
Протокол Teкстовый telnet localhost 9998 Соединение persisten
Почему следует знать Протокол? Если что-то на получается –то проверяем используя telnet Зная Протокол – лучше  оптимизиация Написание тестов и патчей
Последовательность выполнения Создать Индекс Выполнить операцию
Операции = >, >= <, <= +           INSERT =		      UPDATE SELECT
Пример CREATE  TABLE `test`.`test` (   `keyid` VARCHAR(45),   `value` VARCHAR(45),   `code` INT NULL ,   `code2` varchar(32) ,   PRIMARY KEY (`keyid`) ,   INDEX `code`  (`code` ASC)    INDEX `code2`  (`code`, `code2`)  )
Создание индекса P <indexid> <dbname> <tablename> <indexname> <columns> Разделитель ab P 0 test test PRIMARY keyid,value P 1 test test code keyid,code P 3 test test code2 keyid,code,code2
Простая выборка <indexid> <op> <vlen> <v1> ... <vn> <limit> <offset>  >P 1 test test code keyid,code SELECT keyid,value  FROM  test.test WHERE code = ‘000123’ >1 = 1  000123
Простая выборка <indexid> <op> <vlen> <v1> ... <vn> <limit> <offset>  >P 1 test test code keyid,code SELECT keyid,code FROM test.test WHERE code = 10 LIMIT 10 >1 = 1  10 10
Простая выборка <indexid> <op> <vlen> <v1> ... <vn> <limit> <offset>  >P 2 test test code keyid,code,code2 SELECT keyid,code,code2 FROM test.test WHERE code = 10 AND code2=‘a’ LIMIT 10 >2	=	2	10	a	10
Формат ответа  <errorcode> <numcols> <r1> ...<rn> 0 - успех Разделитель ab P	0	test	test	PRIMARY	code,code2,keyid 0	1 0	=	1       100012 0	3	67	c	100012
Формат ответа  <errorcode> <numcols> <r1> ...<rn> P	1	test	test	code	code,code2,keyid 0	1 1 >  1	90	10 1	3 100200 91 a     100258	91 a	  10027… 10 групп по 3
Вставка  <indexid> '+' <vlen> <v1> ... <vn> Пишем в пишущий порт  telnet localhost 9999 0 1 - успех Разделитель ab P	0	test	test	PRIMARY	code,code2,keyid 0	1 0	+       3       1       f       102113       							 0	1
Удаление / Обновление  <indexid> <op> <vlen> <v1> ... <vn> <limit> <offset> <mop> <m1> ... <mk> 0 1- успех Модификатор U – update, D – delete P	0	test	test	PRIMARY	code,code2,keyid 0	1 0	=	1   100001	1  0	 D							 0	1 1
Обновление / Удаление  <indexid> <op> <vlen> <v1> ... <vn> <limit> <offset> <mop> <m1> ... <mk> 0 1 <numcols> Модификатор U – update, D – delete P	0	test	test	PRIMARY	code,keyid 0	1 0	=	1 100003	1 0 U	 zzzzzzz	100003 0	1 1 0	=	1 100003 0	2	zzzzzzz	100003
Клиентские библиотеки libhsclient Net::HandlerSocket http://openpear.org/package/Net_HandlerSocket http://github.com/tz-lom/HSPHP 		       http://code.google.com/p/php-handlersocket/
Клиентские библиотеки https://github.com/kryton/java-handlersocket-client http://pypi.python.org/pypi/python-handler-socket 		        http://packages.python.org/python-handler-socket/ 		        https://github.com/winebarrel/ruby-handlersocket 		        https://github.com/miyucy/handlersocket 		        https://github.com/igrigorik/em-handlersocket 		        https://github.com/quake/active_record_handlersocket https://github.com/koichik/node-handlersocket
Примеры использования Формированиефронтэнда 	 (список товаров)   PHP + HS Поиск товаров по характеристикам PHP + Sphinx + HS Автокомплит(список товаров)  JS + nginx + HS
Формирование фронтэнда Список товаров: $hs->openIndex(0, $dbname, 'good', 'PRIMARY', 'id,title,price,count'); $hs->openIndex(1, $dbname, 'description', 'PRIMARY', 'good_id,description'); $priceItems= $hs->executeSingle(0, '=', array('1'),20); foreach( $priceItemsas &$item ) { $item[’6'] = $hs->executeSingle(1, '=', array($item['0'], $lang_id)); }
Поиск товара Поиск по индексу модели (Sphinx) Поиск индексу характеристики(Sphinx) Выборка товара по idHandlerSocket (см. формирование фронтэнда) $pricItems= $sphinx->Query( $q); foreach ( $pricItemsIdas$id ) {     $item[] = $hs->executeSingle(1, '=', array($id)); }
Автокомплит ( ngx_hsjson ) JS формирует HTTP запросGET /autocomplete/sie[mens] Модуль nginxформирует запрос P 0 shop brands name,id                                            0 >= 1 1 sie 10 HS возвращает результат0 2 siemens 32 Модуль nginxформирует ответJSON {“name”: “Siemens”, “id”: 32}
Модуль ngx_handlersocket_json https://github.com/akalend/ngx_http_handlersocket_json_module location ~ /cities/(.+)/$  { hs_json;               		# enable module hs_json_host 127.0.0.1;# IP хоста hs_json_port 9998;	#порт hs_json_db test;		#БД hs_json_table city;		#имя таблицы hs_json_index name;	#имя индекса hs_json_fieldsname,id;	# список полей hs_json_op "=”;		#операция hs_json_limit 10; 		# аналог limit MySQL hs_request$1;     		# запрос }
Аналог InnoDb-memcached MySQL 5.6.2 – экспериментальная (12.04) Используется InnoDb-API MemcachedПротокол Настройка через таблицы		 conteyners, config_options, cache_policies
Структура InnoDb-memcached
Сравнение с аналогами noSQL
Сравнение с NoSQL
Чтение 9998/9999 port 100K по 32B
Ссылки http://yoshinorimatsunobu.blogspot.com/search/label/handlersocket http://www.slideshare.net/akirahiguchi/handlersocket-plugin-for-mysql-4664154 http://www.percona.com/docs/wiki/percona-server%3Afeatures%3Aspecial%3Ahandlersocket http://habrahabr.ru/blogs/nosql/113040/ http://l-o-n-g.livejournal.com/153756.html
HandlerSocket ,[object Object]
Ускоряет обращение к MySQL 	    более чем в десятки раз

More Related Content

Recently uploaded (9)

СИСТЕМА ОЦЕНКИ УЯЗВИМОСТЕЙ CVSS 4.0 / CVSS v4.0 [RU].pdf
СИСТЕМА ОЦЕНКИ УЯЗВИМОСТЕЙ CVSS 4.0 / CVSS v4.0 [RU].pdfСИСТЕМА ОЦЕНКИ УЯЗВИМОСТЕЙ CVSS 4.0 / CVSS v4.0 [RU].pdf
СИСТЕМА ОЦЕНКИ УЯЗВИМОСТЕЙ CVSS 4.0 / CVSS v4.0 [RU].pdf
 
MS Navigating Incident Response [RU].pdf
MS Navigating Incident Response [RU].pdfMS Navigating Incident Response [RU].pdf
MS Navigating Incident Response [RU].pdf
 
Ransomware_Q3 2023. The report [RU].pdf
Ransomware_Q3 2023.  The report [RU].pdfRansomware_Q3 2023.  The report [RU].pdf
Ransomware_Q3 2023. The report [RU].pdf
 
Malware. DCRAT (DARK CRYSTAL RAT) [RU].pdf
Malware. DCRAT (DARK CRYSTAL RAT) [RU].pdfMalware. DCRAT (DARK CRYSTAL RAT) [RU].pdf
Malware. DCRAT (DARK CRYSTAL RAT) [RU].pdf
 
Cyberprint. Dark Pink Apt Group [RU].pdf
Cyberprint. Dark Pink Apt Group [RU].pdfCyberprint. Dark Pink Apt Group [RU].pdf
Cyberprint. Dark Pink Apt Group [RU].pdf
 
2023 Q4. The Ransomware report. [RU].pdf
2023 Q4. The Ransomware report. [RU].pdf2023 Q4. The Ransomware report. [RU].pdf
2023 Q4. The Ransomware report. [RU].pdf
 
Cyber Defense Doctrine Managing the Risk Full Applied Guide to Organizational...
Cyber Defense Doctrine Managing the Risk Full Applied Guide to Organizational...Cyber Defense Doctrine Managing the Risk Full Applied Guide to Organizational...
Cyber Defense Doctrine Managing the Risk Full Applied Guide to Organizational...
 
CVE. The Fortra's GoAnywhere MFT [RU].pdf
CVE. The Fortra's GoAnywhere MFT [RU].pdfCVE. The Fortra's GoAnywhere MFT [RU].pdf
CVE. The Fortra's GoAnywhere MFT [RU].pdf
 
ИСТОЧНИКИ ИННОВАЦИОННОСТИ КИТАЯ (ПО ВЕРСИИ DGAP) | The Sources of China’s Inn...
ИСТОЧНИКИ ИННОВАЦИОННОСТИ КИТАЯ (ПО ВЕРСИИ DGAP) | The Sources of China’s Inn...ИСТОЧНИКИ ИННОВАЦИОННОСТИ КИТАЯ (ПО ВЕРСИИ DGAP) | The Sources of China’s Inn...
ИСТОЧНИКИ ИННОВАЦИОННОСТИ КИТАЯ (ПО ВЕРСИИ DGAP) | The Sources of China’s Inn...
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Ускоряем MySQL в десятки раз с использованием HandlerSocket

Editor's Notes

  1. Найти ссылки!!!
  2. Найти ссылки!!!
  3. Найти ссылки!!!
  4. Найти ссылки!!!
  5. Найти ссылки!!!
  6. Найти ссылки!!!
  7. Найти ссылки!!!
  8. Найти ссылки!!!
  9. Найти ссылки!!!
  10. Найти ссылки!!!
  11. Найти ссылки!!!
  12. Найти ссылки!!!