使用Pushy進行APNs消息推送

APNs

最近對項目組的老的蘋果IOS推送進行了升級修改??戳丝刺O果的接口文檔,感覺自己直接來寫一個保證穩(wěn)定和高效的接口還是有點難度,同時為了避免重復(fù)造輪子(懶),囧....調(diào)研了一些開源常用的庫之后,選擇了Turo團隊開發(fā)和維護的pushy。

APNs和Pushy

蘋果設(shè)備的消息推送是依靠蘋果的APNs(Apple Push Notification service)服務(wù)的,APNs的官方簡介如下:

Apple Push Notification service (APNs) is the centerpiece of the remote notifications feature. It is a robust, secure, and highly efficient service for app developers to propagate information to iOS (and, indirectly, watchOS), tvOS, and macOS devices.

IOS設(shè)備(tvOS、macOS)上的所有消息推送都需要經(jīng)過APNs,APNs服務(wù)確實非常厲害,每天需要推送上百億的消息,可靠、安全、高效。就算是微信和QQ這種用戶級別的即時通訊app在程序沒有啟動或者后臺運行過程中也是需要使用APNs的(當程序啟動時,使用自己建立的長連接),只不過騰訊優(yōu)化了整條從他們服務(wù)器到蘋果服務(wù)器的線路而已,所以覺得推送要快(參考知乎)。

項目組老的蘋果推送服務(wù)使用的是蘋果以前的基于二進制socket的APNs,同時使用的是一個javapns的開源庫,這個javapns貌似效果不是很好,在網(wǎng)上也有人有過討論。javapns現(xiàn)在也停止維護DEPRECATED掉了。作者建議轉(zhuǎn)向基于蘋果新APNs服務(wù)的庫。

蘋果新APNs基于HTTP/2,通過連接復(fù)用,更加高效,當然還有其它方面的優(yōu)化和改善,可以參考APNs的一篇介紹,講解的比較清楚。

再說一下我們使用的Pushy,官方簡介如下:

Pushy is a Java library for sending APNs (iOS, macOS, and Safari) push notifications. It is written and maintained by the engineers at Turo......We believe that Pushy is already the best tool for sending APNs push notifications from Java applications, and we hope you'll help us make it even better via bug reports and pull requests.

Pushy的文檔和說明很全,討論也很活躍,作者基本有問必答,大部分疑問都可以找到答案,使用難度也不大。

使用Pushy進行APNs消息推送

首先加入包

<dependency>
    <groupId>com.turo</groupId>
    <artifactId>pushy</artifactId>
    <version>0.11.1</version>
</dependency>

身份認證

蘋果APNs提供了兩種認證的方式:基于JWT的身份信息token認證和基于證書的身份認證。Pushy也同樣支持這兩種認證方式,這里我們使用證書認證方式,關(guān)于token認證方式可以查看Pushy的文檔。

如何獲取蘋果APNs身份認證證書可以查考官方文檔。

Pushy使用

ApnsClient apnsClient = new ApnsClientBuilder()
    .setClientCredentials(new File("/path/to/certificate.p12"), "p12-file-password")
    .build();

ps. 這里的setClientCredentials函數(shù)也可以支持傳入一個InputStream和證書密碼。

同時也可以通過setApnsServer函數(shù)來指定是開發(fā)環(huán)境還是生產(chǎn)環(huán)境:

ApnsClient apnsClient = new ApnsClientBuilder().setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
    .setClientCredentials(new File("/path/to/certificate.p12"), "p12-file-password")
    .build();

Pushy是基于Netty的,通過ApnsClientBuilder我們可以根據(jù)需要來修改ApnsClient的連接數(shù)和EventLoopGroups的線程數(shù)。

EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
ApnsClient apnsClient = new ApnsClientBuilder()
        .setClientCredentials(new File("/path/to/certificate.p12"), "p12-file-password")
        .setConcurrentConnections(4).setEventLoopGroup(eventLoopGroup).build();

關(guān)于連接數(shù)和EventLoopGroup線程數(shù)官網(wǎng)有如下的說明,簡單來說,不要配置EventLoopGroups的線程數(shù)超過APNs連接數(shù)。

Because connections are bound to a single event loop (which is bound to a single thread), it never makes sense to give an ApnsClient more threads in an event loop than concurrent connections. A client with an eight-thread EventLoopGroup that is configured to maintain only one connection will use one thread from the group, but the other seven will remain idle. Opening a large number of connections on a small number of threads will likely reduce overall efficiency by increasing competition for CPU time.

關(guān)于消息的推送,注意一定要使用異步操作,Pushy發(fā)送消息會返回一個Netty Future對象,通過它可以拿到消息發(fā)送的情況。

for (final ApnsPushNotification pushNotification : collectionOfPushNotifications) {
    final Future sendNotificationFuture = apnsClient.sendNotification(pushNotification);

    sendNotificationFuture.addListener(new GenericFutureListener<Future<PushNotificationResponse>>() {
        
        @Override
        public void operationComplete(final Future<PushNotificationResponse> future) throws Exception {
            // This will get called when the sever has replied and returns immediately
            final PushNotificationResponse response = future.getNow();
        }
    });
}

APNs服務(wù)器可以保證同時發(fā)送1500條消息,當超過這個限制時,Pushy會緩存消息,所以我們不必擔(dān)心異步操作發(fā)送的消息過多(當我們的消息非常多,達到上億時,我們也得做一些控制,避免緩存過大,內(nèi)存不足,Pushy給出了使用Semaphore的解決方法)。

The APNs server allows for (at the time of this writing) 1,500 notifications in flight at any time. If we hit that limit, Pushy will buffer notifications automatically behind the scenes and send them to the server as in-flight notifications are resolved.

In short, asynchronous operation allows Pushy to make the most of local resources (especially CPU time) by sending notifications as quickly as possible.

以上僅是Pushy的基本用法,在我們的生產(chǎn)環(huán)境中情況可能會更加復(fù)雜,我們可能需要知道什么時候所有推送都完成了,可能需要對推送成功消息進行計數(shù)
,可能需要防止內(nèi)存不足,也可能需要對不同的發(fā)送結(jié)果進行不同處理....不多說,上代碼。

最佳實踐

參考Pushy的官方最佳實踐,我們加入了如下操作:

  • 通過Semaphore來進行流控,防止緩存過大,內(nèi)存不足
  • 通過CountDownLatch來標記消息是否發(fā)送完成
  • 使用AtomicLong完成匿名內(nèi)部類operationComplete方法中的計數(shù)
  • 使用Netty的Future對象進行消息推送結(jié)果的判斷

具體用法參考如下代碼:

public class IOSPush {

    private static final Logger logger = LoggerFactory.getLogger(IOSPush.class);

    private static final ApnsClient apnsClient = null;

    private static final Semaphore semaphore = new Semaphore(10000);

    public void push(final List<String> deviceTokens, String alertTitle, String alertBody) {

        long startTime = System.currentTimeMillis();

        if (apnsClient == null) {
            try {
                EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
                apnsClient = new ApnsClientBuilder().setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
                        .setClientCredentials(new File("/path/to/certificate.p12"), "p12-file-password")
                        .setConcurrentConnections(4).setEventLoopGroup(eventLoopGroup).build();
            } catch (Exception e) {
                logger.error("ios get pushy apns client failed!");
                e.printStackTrace();
            }
        }

        long total = deviceTokens.size();

        final CountDownLatch latch = new CountDownLatch(deviceTokens.size());

        final AtomicLong successCnt = new AtomicLong(0);

        long startPushTime =  System.currentTimeMillis();

        for (String deviceToken : deviceTokens) {
            ApnsPayloadBuilder payloadBuilder = new ApnsPayloadBuilder();
            payloadBuilder.setAlertBody(alertBody);
            payloadBuilder.setAlertTitle(alertTitle);
            
            String payload = payloadBuilder.buildWithDefaultMaximumLength();
            final String token = TokenUtil.sanitizeTokenString(deviceToken);
            SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token, "com.example.myApp", payload);

            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                logger.error("ios push get semaphore failed, deviceToken:{}", deviceToken);
                e.printStackTrace();
            }
            final Future<PushNotificationResponse<SimpleApnsPushNotification>> future = apnsClient.sendNotification(pushNotification);

            future.addListener(new GenericFutureListener<Future<PushNotificationResponse>>() {
                @Override
                public void operationComplete(Future<PushNotificationResponse> pushNotificationResponseFuture) throws Exception {
                    if (future.isSuccess()) {
                        final PushNotificationResponse<SimpleApnsPushNotification> response = future.getNow();
                        if (response.isAccepted()) {
                            successCnt.incrementAndGet();
                        } else {
                            Date invalidTime = response.getTokenInvalidationTimestamp();
                            logger.error("Notification rejected by the APNs gateway: " + response.getRejectionReason());
                            if (invalidTime != null) {
                                logger.error("\t…and the token is invalid as of " + response.getTokenInvalidationTimestamp());
                            }
                        }
                    } else {
                        logger.error("send notification device token={} is failed {} ", token, future.cause().getMessage());
                    }
                    latch.countDown();
                    semaphore.release();
                }
            });
        }

        try {
            latch.await(20, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            logger.error("ios push latch await failed!");
            e.printStackTrace();
        }

        long endPushTime = System.currentTimeMillis();

        logger.info("test pushMessage success. [共推送" + total + "個][成功" + (successCnt.get()) + "個], 
            totalcost= " + (endPushTime - startTime) + ", pushCost=" + (endPushTime - startPushTime));
    }
}

  • 關(guān)于多線程調(diào)用client

Pushy ApnsClient是線程安全的,可以使用多線程來調(diào)用

  • 關(guān)于創(chuàng)建多個client

創(chuàng)建多個client是可以加快發(fā)送速度的,但是提升并不大,作者建議:

ApnsClient instances are designed to stick around for a long time. They're thread-safe and can be shared between many threads in a large application. We recommend creating a single client (per APNs certificate/key), then keeping that client around for the lifetime of your application.

  • 關(guān)于APNs響應(yīng)信息(錯誤信息)

可以查看官網(wǎng)的error code表格(鏈接),了解出錯情況,及時調(diào)整。

Pushy性能

作者在Google討論組中說Pushy推送可以單核單線程達到10k/s-20k/s,如下圖所示:

pushy-discuss

作者關(guān)于創(chuàng)建多client的建議及Pushy性能描述

但是可能是網(wǎng)絡(luò)或其他原因,我的測試結(jié)果沒有這么好,把測試結(jié)果貼出來,僅供參考(時間ms):

ps. 由于是測試,沒有大量的設(shè)備可以用于群發(fā)推送測試,所以以往一個設(shè)備發(fā)送多條推送替代。這里短時間往一個設(shè)備發(fā)送大量的推送,APNs會報TooManyRequests錯誤,Too many requests were made consecutively to the same device token。所以會有少量消息無法發(fā)出。

ps. 這里的推送時間,沒有加上client初始化的時間。

ps. 消息推送時間與被推消息的大小有關(guān)系,這里我在測試時沒有控制消息變量(都是我瞎填的,都是很短的消息)所以數(shù)據(jù)僅供參考。

  • ConcurrentConnections: 1, EventLoopGroup Thread: 1
推送1個設(shè)備 推送13個設(shè)備 同一設(shè)備推100條 同一設(shè)備推1000條
平均推送成功(個) 1 13 100 998
平均推送耗時(ms) 222 500 654 3200
  • ConcurrentConnections: 5, EventLoopGroup Thread: 1
推送1個設(shè)備 推送13個設(shè)備 同一設(shè)備推100條 同一設(shè)備推1000條
平均推送成功(個) 1 13 100 999
平均推送耗時(ms) 310 330 1600 1200
  • ConcurrentConnections: 4, EventLoopGroup Thread: 4
推送1個設(shè)備 推送13個設(shè)備 同一設(shè)備推100條 同一設(shè)備推1000條
平均推送成功(個) 1 13 100 999
平均推送耗時(ms) 250 343 700 1700

關(guān)于性能優(yōu)化也可以看看官網(wǎng)作者的建議:Threads, concurrent connections, and performance

大家有測試的數(shù)據(jù)也可以分享出來一起討論一下。

今天(12.11)又測了一下,推送給3個設(shè)備,每個重復(fù)推送1000條,共3000條,結(jié)果如下(時間為ms):

thread/connection No.1 No.2 No.3 No.4 No.5 No.6 No.7 No.8 No.9 No.10 Avg
1/1 12903 12782 10181 10393 11292 13608 - - - - 11859.8
4/4 2861 3289 6258 5488 6649 6113 7042 5393 4591 7269 5495.3
20/20 1575 1456 1640 2761 2321 2154 1796 1634 2440 2114 1989.1
40/40 1535 2134 3312 2311 1553 2088 1734 1834 1530 1724 1975.5

同時測了一下,給這3個設(shè)備重復(fù)推送100000條消息,共300000條的時間,結(jié)果如下(時間為ms):

thread/connection No.1
20/20 43547

思考

蘋果APNs一直在更新優(yōu)化,一致在擁抱新技術(shù)(HTTP/2,JWT等),是一個非常了不起的服務(wù)。

自己來直接調(diào)用APNs服務(wù)來達到生成環(huán)境要求還是有點困難。Turo給我們提供了一個很好的Java庫:Pushy。Pushy還有一些其他的功能與用法(Metrics、proxy、Logging...),總體來說還是非常不錯的。

同時感覺我們使用Pushy還可以調(diào)優(yōu)...


2017/12/07 done

此文章也同步至個人Github博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容