Каждый разработчик рано или поздно сталкивается с предметно-ориентированными языками (DSL). Мы разберемся, зачем же нам нужны DSL, и какие проблемы они нам помогают решать. Поймем, в каких случаях нам стоит разрабатывать свой язык, а в каких — использовать уже существующий. Попробуем провести грань и решить, где у нас просто библиотека, а где — предметно ориентированный язык. Придумаем свой DSL и сравним различные подходы к работе с ним в Python. Увидим, как работают лексический и синтаксический анализаторы. Обязательно поговорим про то, как облегчить жизнь пользователям нашего языка. Как сделать информативными сообщения об ошибках? Как тестировать сценарии, написанные на нашем языке? На эти вопросы мы сможем дать ответ.
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016Loïc Knuchel
Vous commencez à en entendre parler de plus en plus mais vous avez encore du mal à voir ce que c’est et à comprendre de que ça change concrètement, ce talk est fait pour vous !!!
La programmation fonctionnelle est une manière de programmer basée sur les fonctions qui permet de faire du code vraiment modulaire, améliorer la qualité et limiter les bugs. Vous ne me croyez pas ? Venez voir cette session !
Каждый разработчик рано или поздно сталкивается с предметно-ориентированными языками (DSL). Мы разберемся, зачем же нам нужны DSL, и какие проблемы они нам помогают решать. Поймем, в каких случаях нам стоит разрабатывать свой язык, а в каких — использовать уже существующий. Попробуем провести грань и решить, где у нас просто библиотека, а где — предметно ориентированный язык. Придумаем свой DSL и сравним различные подходы к работе с ним в Python. Увидим, как работают лексический и синтаксический анализаторы. Обязательно поговорим про то, как облегчить жизнь пользователям нашего языка. Как сделать информативными сообщения об ошибках? Как тестировать сценарии, написанные на нашем языке? На эти вопросы мы сможем дать ответ.
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016Loïc Knuchel
Vous commencez à en entendre parler de plus en plus mais vous avez encore du mal à voir ce que c’est et à comprendre de que ça change concrètement, ce talk est fait pour vous !!!
La programmation fonctionnelle est une manière de programmer basée sur les fonctions qui permet de faire du code vraiment modulaire, améliorer la qualité et limiter les bugs. Vous ne me croyez pas ? Venez voir cette session !
Comment Transformer vos boucles Objective-C en “collection pipelines” en utilisant le framework BlocksKit (ou Swift), par Mathieu Godart (votre serviteur). Cette présentation s’inspire de la série d’articles publiée par Martin Fowler, Refactoring with Loops and Collection Pipelines (http://martinfowler.com/articles/refactoring-pipelines.html).
Anatomy of the loadable kernel module (lkm)Adrian Huang
Talk about how Linux kernel invokes your module's init function.
Note: When you view the the slide deck via web browser, the screenshots may be blurred. You can download and view them offline (Screenshots are clear).
La présentation a pour but de revenir sur différents aspects avancés de Doctrine mis en oeuvre au sein de projets Symfony 2.x/3.
Elle abordera, entre autres, les éléments suivants :
Étendre le vocabulaire DQL (spécifiquement ou à l'aide de bundles existants)
Utiliser les différents listeners existants (annotations, listeners, subscribers, utilisation de l'UOW de Doctrine lors d'un flush, etc.)
Créer des hydrateurs spécifiques ou des entités partielles pour améliorer les performances sur certaines opérations.
Astuces diverses pour améliorer les performances (désactivation des logs, etc.)
Pernah bingung gimana caranya sebuah framework menghasilkan sebuah kode output yang berbeda dengan kode yang kamu tulis? Penasaran sebetulnya apa yang terjadi dibalik layar dan gimana caranya kamu bisa belajar dari hal itu untuk memperbaiki kode yang kamu hasilkan?
Наверное каждый периодически сталкивается с проблемами асинхронности и обработкой ошибок при построении своего JavaScript приложения. Рассмотрим, как фреймворк Koa поможет решить нам данные вопросы на бэкенде с помощью генераторов. Какие имеются преимущества и недостатки по сравнению с Express. Расскажу на личном опыте, стоит или не стоит переходить на данный фреймворк.
Доклад с конференции D2D Pizza JS - http://dev2dev.ru/events/8/
Последние полтора года на каждой из наших встреч мы рассказываем о том, почему продуманная и чистая архитектура мобильных приложений — это нужно и важно. За попытками спроектировать серебряную пулю мы очень часто забываем — или просто не уделяем достаточно внимания менее заметной части нашего кода — тестам.
Егор Толстой расскажет о том, почему не стоит обделять вниманием unit-тесты, как подходить к их проектированию и осуществлять постепенный рефакторинг. Выступление, как обычно, подкреплено зарядом личной боли и опыта от поддержки базы в 3.000 unit-тестов на одном проекте и 1.000 на другом.
Rambler.iOS - митапы iOS-разработчиков, организуемые компанией RAMBLER&Co.
Недавно было открыто несколько новых метапрограмных техник в C++, позволяющих реализовать рефлексию, работающую "из коробки". В докладе я расскажу об этих техниках, покажу примеры использования и расскажу об их применимости в C++17. Желающие уже сейчас могут начать экспериментировать с рефлексией, используя библиотеку https://github.com/apolukhin/magic_get
1. Introduction to Lua and it's features
2. OpenResty: full-fledged web application server
3. Installation and "Hello World"
4. Nonblocking
5. Reconstruction of infov
6. Configuration skills
7. Table and JSON output problem
8. DNS and Hosts parser
9. More features
Comment Transformer vos boucles Objective-C en “collection pipelines” en utilisant le framework BlocksKit (ou Swift), par Mathieu Godart (votre serviteur). Cette présentation s’inspire de la série d’articles publiée par Martin Fowler, Refactoring with Loops and Collection Pipelines (http://martinfowler.com/articles/refactoring-pipelines.html).
Anatomy of the loadable kernel module (lkm)Adrian Huang
Talk about how Linux kernel invokes your module's init function.
Note: When you view the the slide deck via web browser, the screenshots may be blurred. You can download and view them offline (Screenshots are clear).
La présentation a pour but de revenir sur différents aspects avancés de Doctrine mis en oeuvre au sein de projets Symfony 2.x/3.
Elle abordera, entre autres, les éléments suivants :
Étendre le vocabulaire DQL (spécifiquement ou à l'aide de bundles existants)
Utiliser les différents listeners existants (annotations, listeners, subscribers, utilisation de l'UOW de Doctrine lors d'un flush, etc.)
Créer des hydrateurs spécifiques ou des entités partielles pour améliorer les performances sur certaines opérations.
Astuces diverses pour améliorer les performances (désactivation des logs, etc.)
Pernah bingung gimana caranya sebuah framework menghasilkan sebuah kode output yang berbeda dengan kode yang kamu tulis? Penasaran sebetulnya apa yang terjadi dibalik layar dan gimana caranya kamu bisa belajar dari hal itu untuk memperbaiki kode yang kamu hasilkan?
Наверное каждый периодически сталкивается с проблемами асинхронности и обработкой ошибок при построении своего JavaScript приложения. Рассмотрим, как фреймворк Koa поможет решить нам данные вопросы на бэкенде с помощью генераторов. Какие имеются преимущества и недостатки по сравнению с Express. Расскажу на личном опыте, стоит или не стоит переходить на данный фреймворк.
Доклад с конференции D2D Pizza JS - http://dev2dev.ru/events/8/
Последние полтора года на каждой из наших встреч мы рассказываем о том, почему продуманная и чистая архитектура мобильных приложений — это нужно и важно. За попытками спроектировать серебряную пулю мы очень часто забываем — или просто не уделяем достаточно внимания менее заметной части нашего кода — тестам.
Егор Толстой расскажет о том, почему не стоит обделять вниманием unit-тесты, как подходить к их проектированию и осуществлять постепенный рефакторинг. Выступление, как обычно, подкреплено зарядом личной боли и опыта от поддержки базы в 3.000 unit-тестов на одном проекте и 1.000 на другом.
Rambler.iOS - митапы iOS-разработчиков, организуемые компанией RAMBLER&Co.
Недавно было открыто несколько новых метапрограмных техник в C++, позволяющих реализовать рефлексию, работающую "из коробки". В докладе я расскажу об этих техниках, покажу примеры использования и расскажу об их применимости в C++17. Желающие уже сейчас могут начать экспериментировать с рефлексией, используя библиотеку https://github.com/apolukhin/magic_get
1. Introduction to Lua and it's features
2. OpenResty: full-fledged web application server
3. Installation and "Hello World"
4. Nonblocking
5. Reconstruction of infov
6. Configuration skills
7. Table and JSON output problem
8. DNS and Hosts parser
9. More features
This document discusses using ngx_lua with UPYUN CDN. It provides examples of using Lua with Nginx for tasks like caching, health checking, and configuration as a service. Key points include using Lua for base64 encoding, Redis lookups, and upstream health checking. Lua provides a more flexible alternative to C modules for tasks like these by leveraging its embedding in Nginx via ngx_lua.
The document lists various metrics for measuring popularity and growth on Facebook in July 2011, including the top 10 most popular applications, pages, and application developers as well as the fastest growing and slowest growing pages at the time. It provides contact information for Dave Nattriss to answer any questions about the Facebook metrics.
The document discusses the results of a study on the effects of exercise on memory and thinking abilities in older adults. The study found that regular exercise can help reduce the decline in thinking abilities that often occurs with age. Older adults who exercised regularly performed better on cognitive tests than those who did not exercise regularly.
1) The document provides several recipes that incorporate lavender, including lavender coffee cake, lavender oatmeal, lavender vegetable scrambled eggs, lavender sugar cookies, lavender pound cake, lemonade with lavender, lavender sugar, roasted potatoes with herbs of Provence, roasted pork chops with herbs of Provence, chocolate chip cookies with lavender, and lemon poppy seed bread.
2) The recipes provide instructions for incorporating dried or fresh lavender into baked goods, drinks, main dishes, and side dishes.
3) Many of the recipes are accompanied by additional preparation or serving suggestions.
Este documento contiene un plano de un departamento ubicado en el primer piso del edificio Cordoba, con detalles como baños, cocina, comedor, dormitorios y un estacionamiento asignado. También muestra las áreas comunes del complejo como quincho, playa, club house y zonas de esparcimiento.
This document provides an overview of virtual reality, including its foundations in human senses and perception. It describes key VR terminology and technologies that enable VR like head-mounted displays. Applications of VR discussed include education, training, simulations, teleoperation and more. Research areas are also outlined such as modeling of materials, human-computer interfaces, haptics, and visualization techniques.
O documento descreve um blog sobre retratos artísticos feitos por Sheila Santos usando lápis pastel e carvão. O blog inclui um auto-retrato feito por Philippe e destaca retratos como um presente inigualável.
FLIBS 2008 Presentation / FTZ & Yacht Importationsmterorotua
The document summarizes the process for entries and withdrawals from a foreign trade zone. It discusses:
1) The required forms for entries (CBP 214 and 7512) and withdrawals (CBP 216).
2) How merchandise can be moved in-bond within the US or for export using form 7512.
3) When a consumption entry (CBP 3461) is necessary to pay duties.
It also provides an overview of advantages of using a foreign trade zone and the different processes for importing yachts, including temporary importations, dutiable importations, duty free trade agreements, and boat show bonds.
This document outlines training, coaching, and consultancy services provided to help implement strategies, improve attitudes and behaviors, and manage organizational change. A range of tailored trainings are provided in areas like communication, leadership, sales, and teambuilding. Individual and team coaching is also available. Consultancy services can help with values, culture, performance, and change. The company believes in enthusiasm, transparency, and respect, and trainers have senior-level experience and a pragmatic field-based approach. Services are delivered from an exceptional environment located 30km from Brussels and include regular assessments to ensure quality and consistency.
This document provides a timeline and overview of Anglo-Irish relations from the 11th century up until the early 20th century. It describes the various invasions and periods of English and Irish rule over the island. Key events included the Anglo-Norman invasion in 1171, Henry VIII declaring himself King of Ireland in 1541, several rebellions against English rule, the Acts of Union in 1801, the push for Catholic emancipation, and the eventual partition of Ireland and establishment of separate parliaments for Northern Ireland and what would become the Irish Free State through the Government of Ireland Act in 1920.
The document discusses search engines and digital libraries. It begins by defining search engines and how they work, using crawlers to index web pages and returning search results based on keywords. It then discusses how digital libraries are similar, allowing searches of their online collections. The document provides examples of large academic digital libraries that contain searchable article databases, ebooks, and other digital materials.
Mavis A. Bellido was awarded two certificates for her work as a school guidance counselor and LAC leader. The first certificate names her as an outstanding guidance counselor in the District of Pangil-Pakil for over 10 years of exemplary service as the guidance counselor at V.O. de Guia Jr. Mem. Elem. School. The second certificate names her as the best school LAC leader for school year 2008-2009 for her work establishing the school's learning resource center and supporting her colleagues. Both certificates were issued by education officials in the Region IVA-CALABARZON division.
Ryan E. Crumley is a professional with experience in various fields. He has a background in marketing, sales, and business development. Mr. Crumley is skilled at developing strategies, managing projects, and achieving goals.
The document discusses the introduction of PVC membrane roofing systems in India as a new approach to roofing that addresses challenges from increased construction demands. PVC membrane roofing provides benefits over conventional systems like better performance for re-roofing, metal decks, roof gardens, and energy/green building requirements. It has a long history of use in Europe and is thermoplastic, allowing seams to be heat welded for a watertight bond. The new system offers construction industries a solution that considers requirements for speed, safety, low maintenance and cost while providing durability.
The document provides guidance for leading a social entrepreneurship and community service trip to Laos. It emphasizes motivating team members, ensuring tasks are completed on time, minimizing conflicts, and caring for the welfare of the team. It also stresses building trust, setting a good example, communicating values, and recognizing team members' efforts to keep morale high and resolve any issues that may arise during the trip.
This document discusses load balancing with LVS (Linux Virtual Server) and troubleshooting TCP/IP issues. It includes log output showing LVS routing requests to backends, configuration for routing with IPVSADM and Nginx, and recommendations for disabling LRO/GRO features and adjusting TCP settings to address retransmission issues. Commands like tcpdump, netstat, and ethtool are referenced for analyzing network traffic and interface settings.
This document provides 40 shortcuts for Xcode 6.x. Some of the most commonly used shortcuts include Command + N to create new files, Command + O to open files, Command + Click to go to definitions, Command + F to find in files, Command + B to build projects, and Command + R to build and run projects. The document encourages practicing these shortcuts to improve efficiency when coding in Xcode.
1. What web caching means and includes
2. Why use caching
3. File caching
4. Share caching
5. Local caching
6. Memcached and its usage
7. TTServer and KTServer
8. Redis VS SSDB
9. CDN cachings
10. Twemproxy
11. Programming skills and tips
1. What does millions visits means?
2. How to know the problem? Tools?
3. Steps for emergency repair
4. The real problem is “Socket”
5. Profiling with XHProf
6. Cachings and twemproxy
7. Summarize of skills
1. Comment: the UGC system
2. Pages/Channels that use the comment system
3. The architecture
4. The APIs and Entries
5. MongoDB and ObjectId
6. Comments "Gailou"
7. Indexes of the big tables
1. A brief introduction of Git (SVN, CVCS, DVCS etc.)
2. Git/TortoiseGit/msysgit installations
3. A complete guide of Git operations
4. The Branches and HEAD
5. Remote and local repository
6. Rebase and submodules etc.
7. Some Skills and Experience
PHP Coding Standard and 50+ Programming SkillsHo Kim
1. How and Why to write good code?
2. Coding standard based on ZendFramework and real world practise.
3. PHP programming skills from daily coding.
4. Some security tips
5. Some optimization tips
3. 逻辑运算符 and、or 和 not 是经常隐藏 bug 的地方,比
如:
if (type(t) == 'table' and t.x == 'abc')
就算 t 不是 table 类型,那么 lua 的短路求值也不会对 t
进行求值,所以不会引发运行时错误
4. 用 xpcall debug
function errorFunc()
local a = 20
print(a[10])
end
function errorHandle()
print(debug.traceback())
end
if xpcall(errorFunc,errorHandle) then
print("This is OK.")
else
print("This is error.")
end
8. 简单的写log函数(排重)
local logsUniquify = {} ——是的,这是个全局数组
function log(message, level)
if ngx and type(ngx.log) == 'function' then
local level = level or ngx.EMERG
if not logsUniquify[level .. message] then
ngx.log(level, message)
logsUniquify[level .. message] = true
end
end
return nil
end
14. Sql Injection
local name = ngx.unescape_uri(ngx.var.arg_name)
local quoted_name = ngx.quote_sql_str(name)
local sql = "select * from users where name = " ..
quoted_name
15. htmlspecialchars的实现
function htmlspecialchars(str)
local rs = str or nil
if rs and type(rs) == 'string' then
rs = string.gsub(rs, '&', '&')
rs = string.gsub(rs, '"', '"')
rs = string.gsub(rs, "'", ''')
rs = string.gsub(rs, '<', '<')
rs = string.gsub(rs, '>', '>')
end
return rs
end
19. 过滤 v 中的疑似网址特征
local spos = find(v, 'www') or find(v, '%.')
or find(v, '。') or find(v, '点')
local substring = ''
if spos then
substring = string.sub(s, spos, epos)
substring = g.escapeMagic(substring)
v = string.gsub(s, substring, '')
end
20. Build Queries
bind['so_refer_key'] = g.trim(vinfo['so_refer_key'])
bind['request_from'] = 'info_relate'
bind['wt'] = 'json'
bind['qt'] = 'standard'
bind['56_version'] = ngx.var.arg_rvc
bind['so_refer_key'] = ngx.var.arg_so_refer_key or ''
local param = neturl.buildQuery(bind)
local host = 'related_video.solr.56.com' --
local port = '49715'
local uri = '/solrRelateVideo/select?' .. param
if ngx.var.arg_dg == 'ml' then
print(uri)
end
21. xssfilter
— Filter the XSS attack
local xssfilter = require("lib.xssfilter")
local xss_filter = xssfilter.new()
data['title'] = g.htmlentities(xss_filter:filter(data['title']))
22. Sandbox
— 使用 closure 创建 sandbox (安全运行环境),比如为 io.open 提供权限控制的功能:
do
local oldOpen = io.open
local checkAccess = function (file, mode)
-- check if current user with 'mode' can access the 'file'
end
io.open = function (file, mode)
if checkAccess(file, mode) then
return oldOpen(file, mode)
else
return nil, "access, denied"
end
end
end
27. unpack(2)
— 经典应用 redis 的 hmget :
local tmpVids = {}
for i,v in ipairs(res) do
table.insert(tmpVids, tostring(v['video_id']))
end
local vextinfos = {}
local tbTimes = rds:hmget(rhkey, unpack(tmpVids))
31. Random Pick
function array_rand(tbl, m)
local rs
if type(tbl) == 'table' and next(tbl) ~= nil then
rs = {}
local order = {}
local n = #tbl
for i = 1, n do
order[i] = {rnd = math.random(), idx = i}
end
table.sort(order, function(a,b) return a.rnd < b.rnd end)
for i = 1, m do
if order[i] then rs[i] = order[i].idx end
end
end
return rs
end
32. Intersect by Key
function array_intersect_key(t1, t2)
local rs = t1
if type(t1) == 'table' and type(t2) == 'table' then
rs = {}
for k,v in pairs(t1) do
if t2[k] ~= nil then rs[k] = v end
end
end
return rs
end
33. Deep Compare
function deepcompare(t1, t2)
local ty1 = type(t1)
local ty2 = type(t2)
if ty1 ~= ty2 then return false end
-- non-table types can be directly compared
if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end
-- as well as tables which have the metamethod __eq
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if v2 == nil or not deepcompare(v1,v2) then return false end
end
for k2,v2 in pairs(t2) do
local v1 = t1[k2]
if v1 == nil or not deepcompare(v1,v2) then return false end
end
return true
end
34. 模块初始化与 __index
— 定义模块实例化的方法:
--[[ init module ]]
module(...)
_VERSION = '1.0.0'
--[[ indexed by current module env. ]]
local mt = {__index = _M};
--[[
instantiation
@return table
]]
function new(self)
return setmetatable({}, mt);
end
35. Default Value
function setDefault(table, default)
local mt = {__index = function() return default end }
setmetatable(table,mt)
end
tab = {x = 10, y = 20}
setDefault(tab,0)
print(tab.x,tab.z) --10 0
36. Write Prohibited
setmetatable(_M, {
__newindex = function (table, key, val)
ngx.log(ngx.EMERG, 'attempt to write to undeclared variable "' ..
key .. '" in ' .. table._NAME);
end
})
_M.unexists = "hello" -- 报错:’attempt to write to undeclared variable
"unexists" in $module'
37. Table Traversal
for k,v in g.pairsByKeys(idDel) do
print(k .. ':' .. v .. "n")
end
function pairsByKeys(tb, f)
local a = {}
for n in pairs(tb) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function() -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], tb[a[i]]
end
end
return iter
end
38. Sort by Value
function sortAssoc(tb, order, limit)
local rs = nil
if type(tb) == 'table' then
rs = {}
local tmp = {}
for k,v in pairs(tb) do
table.insert(tmp, {key = k, val = tonumber(v)})
end
if next(tmp) ~= nil then
if order and order == 'DESC' then
table.sort(tmp, function(a, b) return b.val < a.val end)
else
table.sort(tmp, function(a, b) return b.val > a.val end)
end
end
for i,v in ipairs(tmp) do
table.insert(rs, {v['key'], v['val']})
if limit and (i >= limit) then break end
end
end
return rs
end
39. Multi-Array Sorting
local data = {
{id=3, data=421}, {id=23, data=321}, {id=3, data=422}, {id=5, data=321},
{id=1, data=4214}, {id=3, data=44}
}
table.sort(data, function(a, b)
if a['id'] < b['id'] then
return true
elseif a['id'] == b['id'] then
if a['data'] < b['data'] then
return true
else
return false
end
else
return false
end
end)
46. 形参 vs 实参
1. 实参多于形参,多出的部分被忽略
2. 形参多于实参,没被初始化的形参的缺省值为nil
function foo(a, b, c)
print(a, b, c)
end
foo('a', 'b', 'c', 'd') -- 'd' 被忽略
foo('a') -- 这时形参 b 和 c 都是 nil
49. Fastest Trim
function trim(s)
if type(s) == 'string' then
local match = string.match
return match(s,'^()%s*$') and '' or match(s,'^%s*(.*%S)')
end
return s
end
57. How to “continue”?
local bContinue
for k, v in pairs(tbl) do
bContinue = false
......
if not bContinue then
......
if needToContinue then
bContinue = true
end
end
if not bContinue then
-- continue to do things
end
end
58. elseif vs else if
if ... then
else
if ... then
end
end
if ... then
elseif ... then
end
62. Serialize
function serialize(o)
if type(o) == "number" then
io.write(o)
elseif type(o) == "string" then
--string.format函数的"%q"参数可以转义字符串中的元字符。
io.write(string.format("%q",o))
elseif type(o) == "table" then
io.write("{n")
--迭代table中的各个元素,同时递归的写出各个字段的value。
--由此可以看出,这个简单例子可以支持嵌套的table。
for k,v in pairs(o) do
--这样做是为了防止k中包含非法的Lua标识符。
io.write(" ["); serialize(k); io.write("] = ")
serialize(v)
io.write(",n")
end
io.write("}n")
else
error("cannot serialize a " .. type(o))
end
end
63. Size and Seek
1. local f = assert(io.open(filename,"r"))
2. local current = f:seek() --获取当前位置
3. local size = f:seek("end") --获取文件大小
4. f:seek("set",current) --恢复原有的当前位置
64. 读取文件优化
下面是Shell中wc命令的一个简单实现:
local BUFSIZE = 8192
local f = io.input(arg[1]) --打开输入文件
local cc, lc, wc, = 0, 0, 0 --分别计数字符、行和单词
while true do
local lines,rest = f:read(BUFSIZE,"*line")
if not lines then
break
end
if rest then
lines = lines .. rest .. "n"
end
cc = cc + #lines
--计算单词数量
local _, t = string.gsub(lines."%S+","")
wc = wc + t
--计算行数
_,t = string.gsub(line,"n","n")
lc = lc + t
end
print(lc,wc,cc)
66. Socket Connect
-- 用 ngx.socket.tcp 才能百分百支持 nonblocking
local sock = ngx.socket.tcp()
sock:settimeout(1000) -- one second
local ok, err = sock:connect("127.0.0.1", 11211)
local bytes, err = sock:send("flush_allrn")
if not bytes then
ngx.say("failed to send query: ", err)
return
end
local line, err = sock:receive()
if not line then
ngx.say("failed to receive a line: ", err)
return
end
ngx.say("result: ", line)
local ok, err = sock:setkeepalive(60000, 500)
if not ok then
ngx.say("failed to put the connection into pool with pool capacity 500 "
.. "and maximal idle time 60 sec")
return
end
67. Settimeout
sock:settimeout(1000)
ok, err = tcpsock:connect(host, port, options_table?)
sock:settimeout(1000)
bytes, err = tcpsock:send(data)
sock:settimeout(1000)
data, err, partial = tcpsock:receive(size) —读timeout是不会close掉连接的
local reader = sock:receiveuntil("rn--abcedhb")
sock:settimeout(1000)
while true do
……
end
ok, err = tcpsock:close()
69. 协程示例
协程的经典示例:“生产者-消费者”问题:
--消费者
function receive()
local status, value = coroutine.resume(producer) --消费
return value
end
--生产者
function send(x)
coroutine.yield(x) --挂起
end
--协程
producer = coroutine.create(
function()
while true do
local x = io.read() --产生新值
send(x)
end
end)
70. cosocket 读取大数据
local sock, err = ngx.req.socket()
if not sock then
ngx.say("failed to get request socket: ", err)
return
end
sock:settimeout(10000) -- 10 sec timeout
while true do
local chunk, err = sock:receive(4096)
if not chunk then
if err == "closed" then
break
end
ngx.say("faile to read: ", err)
return
end
process_chunk(chunk)
end