使用Houston+Sidekiq做ios消息推送
创建NotifierWorker类
1# app/workers/notifier_worker.rb
2require 'apn_connection'
3class NotifierWorker
4 include Sidekiq::Worker
5
6 APN_POOL = ConnectionPool.new(:size => 2, :timeout => 300) do
7 APNConnection.new
8 end
9
10 def perform(message, custom_data = nil)
11 APN_POOL.with do |connection|
12 token = "<dccec3dd 25936d87 5ed2d16b 75f0785c bdb0b33d 8dd48f1c 72529c00 b1c56a19>"
13 notification = Houston::Notification.new(device: token)
14 notification.alert = message
15 notification.sound = 'default'
16 notification.custom_data = custom_data
17 connection.write(notification.message)
18 end
19 end
20end
创建APNConnection类
1# lib/apn_connection.rb
2class APNConnection
3
4 def initialize
5 setup
6 end
7
8 def setup
9 @uri, @certificate = if Rails.env.production?
10 [
11 Houston::APPLE_PRODUCTION_GATEWAY_URI,
12 File.read("#{Rails.root}/config/shixian-production.pem")
13 ]
14 else
15 [
16 Houston::APPLE_DEVELOPMENT_GATEWAY_URI,
17 File.read("#{Rails.root}/config/shixian-development.pem")
18 ]
19 end
20
21 @connection = Houston::Connection.new(@uri, @certificate, nil)
22 @connection.open
23 end
24
25 def write(data)
26 begin
27 raise "Connection is closed" unless @connection.open?
28 @connection.write(data)
29 rescue Exception => e
30 attempts ||= 0
31 attempts += 1
32
33 if attempts < 5
34 setup
35 retry
36 else
37 raise e
38 end
39 end
40 end
41
42end
使用
1NotifierWorker.perform_async("hello","s" => "1,Notification")