38
@dmytromindra #msugodua WEB В РЕАЛЬНОМ ВРЕМЕНИ С WINDOWS AZURE И NODE.JS Дмитрий Миндра, Lohika ://www.slideshare.net/dmytromindra

Windows Azure and node js

Embed Size (px)

DESCRIPTION

Windows Azure and NodeJS by Dmytro Mindra

Citation preview

Page 1: Windows Azure and node js

@dmytromindra #msugodua

WEB В РЕАЛЬНОМ ВРЕМЕНИ С WINDOWS AZURE И NODE.JS

Дмитрий Миндра, Lohika

http://www.slideshare.net/dmytromindra

Page 2: Windows Azure and node js

@dmytromindra #msugodua

Вы замечательные !

Page 3: Windows Azure and node js

@dmytromindra #msugodua

Для кого этот доклад?

Вам нравится JavaScript

Вы хотите чего-то нового!

Вам нравится Web

Page 4: Windows Azure and node js

@dmytromindra #msugodua

Мустафин Дмитрий

RnD Team Lead

Microsoft Technologies Lab Member

Page 5: Windows Azure and node js

@dmytromindra #msugodua

Нечто

Великолепное ПО

Page 6: Windows Azure and node js

@dmytromindra #msugodua

Посторонись, пресловутый PHP! Долой Java! Старичок Perl, тебе так вообще давно пора на

пенсию. И как же вы уже достали, попсовые Ruby и

Python!

(c) xakep

http://www.xakep.ru/post/53583/

Page 7: Windows Azure and node js

@dmytromindra #msugodua

МыЖдемПеремен

!

Page 8: Windows Azure and node js

@dmytromindra #msugodua

Page 9: Windows Azure and node js

@dmytromindra #msugodua

Node.js&

23 июня 2011

Page 10: Windows Azure and node js

@dmytromindra #msugodua

var http = require('http');

http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');

HELLO WORLD

Page 11: Windows Azure and node js

@dmytromindra #msugodua

ПОЧЕМУ NODE.JS?

Цель Node.JS - обеспечение простого способа создания масштабируемых сетевых программ.

Event Driven

Все асинхронно

Работает на Google V8Официально поддерживается компанией MicrosoftХорошо параллелится (при работе с вводом/выводом)

Page 12: Windows Azure and node js

@dmytromindra #msugodua

АСИНХРОННОСТЬ

Пока выполняется операция, которую надо ждать, Node.JS занимается полезным делом.

Page 13: Windows Azure and node js

@dmytromindra #msugodua

СЛАБЫЕ СТОРОНЫ

У Node.JS есть слабые стороны, о которых надо помнить.

Плохо справляется с тяжелыми вычислительными задачами

Использует только одно ядро процессора (есть утилита Cluster)

Page 14: Windows Azure and node js

@dmytromindra #msugodua

Спагетти кодvar fs = require('fs') , path = require('path') , file1 = "file1.txt“ , file2 = "file2.txt";

// Check if file1 exists, write to file2, // then display new file2 contents. path.exists(file1, function (exists) { if (!exists) throw new Error("No file!"); fs.readFile(file1, function (err, data) { if (err) throw err; fs.writeFile(file2, data, function (err) { if (err) throw err; fs.readFile(file2, function (err, data) { if (err) throw err; console.log(data.toString()); ... }); }); }); });

Page 15: Windows Azure and node js

@dmytromindra #msugodua

ХОРОШИЙ ИНСТРУМЕНТ

Для подходящей задачи.

Важно уметь отличить подходящую задачу от неподходящей.

Page 16: Windows Azure and node js

@dmytromindra #msugodua

Есть ли у нас план?

1. Привет Node!2. Web Проект3. SPA4. Windows Azure5. Socket.IO

Page 17: Windows Azure and node js

@dmytromindra #msugodua

ПЕРВЫЕ ШАГИПора делать

Page 18: Windows Azure and node js

@dmytromindra #msugodua

Node Package Manager

Управляет установкой модулей, например

npm install azure

npm install –g express

Page 19: Windows Azure and node js

@dmytromindra #msugodua

WEB ПРИЛОЖЕНИЯРазработка первого

Page 20: Windows Azure and node js

@dmytromindra #msugodua

Что в меню ?

JavaScript везде. И на сервере, и на клиенте. Некоторые библиотеки используются одновременно и на сервере и на клиенте.

Express (сервер)Jade (сервер)Mustache (сервер , клиент)Sammy.js (клиент)jQuery (клиент)

Page 21: Windows Azure and node js

@dmytromindra #msugodua

ПРОСТОЕ WEB ПРИЛОЖЕНИЕ

Постараемся построить простое веб приложение при помощи Express, Jade и пары заготовок.

Page 22: Windows Azure and node js

@dmytromindra #msugodua

SPA* – приложение-страница

Приложение, состоящее из одной веб страницы и обилия скриптов.

Асинхронно общается с сервером.Не перегружается.

*http://en.wikipedia.org/wiki/Single_Page_Application

Page 23: Windows Azure and node js

@dmytromindra #msugodua

WINDOWS AZUREИнтеграция с

Page 24: Windows Azure and node js

@dmytromindra #msugodua

ПРИСТУПАЕМ К РАБОТЕ

Мы кратко расскажем как: создать новое Windows Azure Node.js приложение

используя инструменты Windows PowerShell

запустить Node приложение локально, используя Windows Azure compute emulator

опубликовать ваше приложение а Windows Azure

Дополнительная информация:

https://www.windowsazure.com/en-us/develop/nodejs/tutorials/getting-started/https://www.windowsazure.com/en-us/develop/nodejs/tutorials/web-app-with-storage/

Page 25: Windows Azure and node js

@dmytromindra #msugodua

ЕСЛИ КОРОТКО, ТОВыполните команду

npm install azure

В файле «c:\node\tasklist\WebRole1\Web.cloud.config» замените тестовые данные на данные вашей учетной записи Azure.

Вы найдете много полезной информации в файле:«C:\node\tasklist\WebRole1\node_modules\azure\README.md»

Создайте новую переменную в вашем JavaScript файле:var azure = require('azure');

Все готово! Поехали !

Page 26: Windows Azure and node js

@dmytromindra #msugodua

СЕРВИС ТАБЛИЦСоздаем сервис: var tableService = azure.createTableService();

Назначаем имя таблице: var myTableName = “MyTable”;

Создаем таблицу:tableService.createTableIfNotExists(myTableName, OnCreatedFunc);

Где OnCreatedFunc является функцией, которая выполнится после создания таблицы (Callback)function OnCreatedFunc(errorObject, createdBoolFlag) {…}

Больше информации по адресу:http://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/table-services/

Page 27: Windows Azure and node js

@dmytromindra #msugodua

ДОБАВЛЯЕМ ЗАПИСЬ В ТАБЛИЦУ

Таблица Azure является контейнером для любого объекта. “PK” является комбинацией Partition и Row ключей.

Объявляем объект: var myObj = { PartitionKey: “MyPartition“, RowKey: “myRowKey“, myProp1: “Dima+", myProp2: “Luba=“, myProp3: “Misha”};

Добавляем объект в таблицу:tableService.insertEntity(

myTableName, myObj, OnMyObjInserted);

Где функция OnMyObjInserted является callback-омfunction OnMyObjInserted(error, serverEntity) {…}

Page 28: Windows Azure and node js

@dmytromindra #msugodua

ОБНОВЛЯЕМ ЗАПИСЬОбъявляем объект с обновленными данными:var myObjUpd = { PartitionKey: “MyPartition“, RowKey: “myRowKey", myProp1: “Dima+", myProp2: “Luba=”, myProp3: “Misha and Margo" };

Обновляем существующую сущность: tableService.updateEntity( myTableName, myObjUpd, OnMyObjUpdated);Функция OnMyObjUpdated – это, как всегда, callback:function OnMyObjUpdated(error, serverEntity) {…}

Подводный камень: вы должны заполнить все поля своего объекта, либо воспользоваться объектом ServerEntity и изменить только необходимые поля!

Page 29: Windows Azure and node js

@dmytromindra #msugodua

ЗАПРАШИВАЕМ ЗАПИСЬОдиночный объект:tableService.queryEntity(myTableName, myPartition, myRowKey, OnEntityQueried);

callback:function OnEntityQueried(error, serverEntity) {…}

Набор объектов:var query = azure.TableQuery.select().from(myTableName)

.where(“PartitionKey eq ?”, “MyPartition”);tableService.queryEntities(query, OnEntitiesQueried);

сallback:function OnEntitiesQueried(error, serverEntities) {…}

Page 30: Windows Azure and node js

@dmytromindra #msugodua

КАК НАСЧЕТ BLOB?Все работает точно так же, как и в таблицах:

var azure = require('azure');var blobService = azure.createBlobService();blobService.createContainerIfNotExists(…);blobService.createBlockBlobFromStream(…);blobService.listBlobs(…);blobService.getBlobToStream(…);blobService.deleteBlob(…);

Подробнееhttp://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/blob-storage/

Page 31: Windows Azure and node js

@dmytromindra #msugodua

SOCKET.IOWEB в реальном времени

Page 32: Windows Azure and node js

@dmytromindra #msugodua

WebSockets

Постоянное подключение к серверу.

Часть стандарта HTML5

Предназначен для построения Real-Time приложений.

http://tools.ietf.org/html/rfc6455

Page 33: Windows Azure and node js

@dmytromindra #msugodua

Что такое SOCKET.IO?

Больше, чем просто WebSockets.

Имеет альтернативные виды транспорта.

Поставляется с клиентской библиотектой.

Виды транспорта:WebSocketFlash SocketAJAX long-pollingAJAX multipart streamingIFrameJSONP polling

Page 34: Windows Azure and node js

@dmytromindra #msugodua

Время действовать

Напишем приложение, работающее в реальном времени.

В нашем случае этим приложением будет обмен мгновенными сообщениями.

Page 35: Windows Azure and node js

@dmytromindra #msugodua

В ЗАКЛЮЧЕНИЕПодводим итоги

Page 36: Windows Azure and node js

@dmytromindra #msugodua

1. JavaScript невероятно популярен. На рынке много программистов.

2. JavaScript будет единым языком и на сервере и на клиенте. Никакого дублирования кода.

3. Асинхронная событийная модель.

Мои аргументы:

Page 37: Windows Azure and node js

@dmytromindra #msugodua

Внеклассное чтение

Как убедить босса?http://nodeguide.com/convincing_the_boss.html

Выбор правильного стиляhttp://stackoverflow.com/questions/5495984/coding-style-guide-for-node-js-apps

Что такое Node?http://stackoverflow.com/questions/1884724/what-is-node-js

Page 38: Windows Azure and node js

@dmytromindra #msugodua

СПАСИБО !Это стоит попробовать!

[email protected]