With tens of millions of clients continuously downloading binaries from our repositories, we decided to offer an OSS client that natively supports these downloads. In this talk, we will share the main challenges in developing a highly-concurrent, resumable, async download library on top of Apache HTTP client. We will cover other libraries we tested and why we decided to reinvent the wheel. We will see important pitfalls we came across when working with HTTP and how using the right combination of techniques can improve performance by an order of magnitude. We will also see why your initial assumptions may completely change when faced with other players on the network. Consider yourself forewarned: lots of HTTP internals, NIO and concurrency ahead!
27. Код! На Java! Распределение
while (!Thread.interrupted()) {
selector.select();
Set selected = selector.selectedKeys();
Iterator it = selected.iterator();
while (it.hasNext())
SelectionKey k = (SelectionKey)(it.next();
((Runnable)(k.attachment())).run();
selected.clear();
}
28. Обработка событий в реакторе –
сложная штука
– Надо помнить состояние
– Буфферизация – надо собирать куски
файлов
– надо координировать события
29.
30. Библиотеки Nio
– В основном серверные
–Netty, grizzly, etc.
– Apache Mina
– Apache HTTP components asyncclient
– Ning http client
31. Библиотеки Nio
– В основном серверные
–Netty, grizzly, etc.
– Apache Mina
– Apache HTTP components asyncclient
– Ning http client
32. – Серверная и клиентская nio
библиотека
– Отпочковалась от netty
– Последний релиз: октябрь 2012
33.
34. Библиотеки Nio
– В основном серверные
–Netty, grizzly, etc
– Apache Mina
– Apache HTTP components asyncclient
– Ning http client
48. Фича/Библиотека Ning client Http Async Client
Матёрость Хорошая Совсем зеленый (начало
2014)
Отмена закачек Легко Не без багов
Мониторинг
прогресса
Не достаточно
мелкие события
Да вот же: onByteReceived()
Документация Оставляет желать
лучшего
Скорее нет, чем есть
Серверная
составляющая
Нет, только клиент org.apache.httpcomponents
httpcore-nio
Но всё таки надо выбирать
68. Закодированное URLEncoder-ом
не раскодируешь обратно…
http://example.com/?query=a&b==c
Нельзя раскодировать обратно после
того, как закодируешь:
http://example.com/?query=a%26b==c
69. Не пользуйтесь
java.net.URLEncoder
“Utility class for HTML form encoding. This
class contains static methods for
converting a String to the
application/x-www-form-
urlencoded MIME format.
For more information about HTML form
encoding, consult the HTML specification.”
87. Уровень ОС
– Защита от дурака: Несколько
приложений скачивают тот же файл в
то же место
– Надо лочить:
–Частично закаченный файл
–Сохраненный на диск прогресс
88. Легко, нам нужен shared lock!
• Один пишет, остальные смотрят читают
93. Локинг на уровне VM
– Закрывать файл должен только один поток
– Процесс закрытия:
– Снять локи ОС
– Закрыть channels
– Переименовать файл в конечный вид (убрать
.part)
– Стереть файл прогресса
94. Локинг на уровне VM
ReentrantReadWriteLock.ReadLock writeToFileLock = rwl.readLock();
ReentrantReadWriteLock.WriteLock closeFileLock = rwl.writeLock();
public void close() throws IOException {
this.closeFileLock.lock();
}
public int write(int partIndex, ByteBuffer buf) {
if (!this.writeToFileLock.tryLock()) {
throw new IllegalStateException("File is being closed");
}
...
}
97. http/2
– В основном стандартизирует spdy от Google
– Компрессия хидеров
– мультиплексирование
– приоритизация
– Сервер пуш
– Ну и прояснить всякие моменты
– Например длинна сжатого контента
100. Линки!
• RTFM: RFC 2616
• САМАЯ ВАЖНАЯ КНИГА (про 1.1):
HTTP: The Definitive Guide
– Amazon
– Safari
• Шаблон «реактор»
• Даг Ли про NIO
• HTTP/2
Editor's Notes
Things that are not simple
Why you dont’s
Just avoid
CURRENT – JBNEXT - YOAV
Events are multiplexed by a single thread dispatcher
TODO send table to back!!!
Hypertext Transfer Protocol -- HTTP/1.1
RFC2616 8.1.4
Browsersgo like:
RAC is not concurrent!
lock beyond the end of file, so we can write while others are reading
avoid OS-dependent no support for shared lock (for concurrent r/w) and fallback to exclusive
+ avoid OS-dependent access effect of exclusive locks (Windoze...)
Allows writing and reading by knowing if someone else is writing
https://community.oracle.com/message/8781694