Last active
February 2, 2022 21:08
-
-
Save rlogwood/8577c4cc680b153ff26b9f9798d35afd to your computer and use it in GitHub Desktop.
Example code from RubyConf 2021 talk "Async Ruby" by Bruno Sutic https://www.youtube.com/watch?v=pzpH_ND-CQM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 100 iterations of six 2 second tasks (600 total tasks) | |
# On my Linux box this ran in 3.567640724s | |
# the large max connections of 100 for Sequel postgres to minimize wait | |
# see RubyConf 2021 - Async Ruby by Bruno Sutic https://www.youtube.com/watch?v=pzpH_ND-CQM | |
# Note: This example code does not include the ssh test included in the talk | |
# as I didn't have a server setup for that | |
# task.async do | |
# Net::SSH.start("191.168.??.??").exec!("sleep 1.5") # takes 2 sec | |
# end | |
require 'async' | |
require 'open-uri' | |
require 'httparty' | |
require 'redis' | |
# require 'net/ssh' | |
require "sequel" | |
DB = Sequel.postgres('mydb', max_connections: 100) | |
Sequel.extension(:fiber_concurrency) | |
time = Time.now | |
iterations = 100 | |
Async do |task| | |
iterations.times do | |
task.async do | |
URI.open('https://httpbin.org/delay/2') | |
end | |
task.async do | |
HTTParty.get('https://httpbin.org/delay/2') | |
end | |
task.async do | |
Redis.new.blpop("abc123", 2) | |
end | |
task.async do | |
DB.run("select pg_sleep(2)") | |
end | |
task.async do | |
sleep 2 | |
end | |
# system commands can run async! | |
task.async do | |
`sleep 2` | |
end | |
end | |
end | |
puts "Duration #{Time.now - time}s" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source "https://rubygems.org" | |
gem 'open-uri' | |
gem 'async' | |
gem 'async-http' | |
gem 'httparty' | |
gem 'redis' | |
# gem 'net-ssh' | |
gem 'sequel' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment