SpringCloud 利用Javapns完成IOS APP消息推送

系统启动时,初始化推送队列:

import javapns.Push;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotifications;
import javapns.notification.transmission.PushQueue;

    /**
     * IOS推送证书路径
     */
    @Value("${push.iosCertPath}")
    private String iosCertPath;
    /**
     * IOS推送证书密码
     */
    @Value("${push.iosCertPassword}")
    private String iosCertPassword;
    /**
     * IOS推送产品模式
     */
    @Value("${push.iosProduction:false}")
    private boolean iosProduction;
    /**
     * IOS推送线程数
     */
    @Value("${push.iosThreads:5}")
    private int iosThreads = 5;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 启动IOS推送队列
        iosPushQueue = Push.queue(iosCertPath, iosCertPassword, iosProduction, iosThreads);
        iosPushQueue.start();
        log.info("IOS推送队列已经启动.");

        // 启动IOS推送守护线程
        Thread iosDaemonThread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(10 * 1000);
                    PushedNotifications result = iosPushQueue.getPushedNotifications();
                    int success = result.getSuccessfulNotifications().size();
                    int failure = result.getFailedNotifications().size();
                    log.info("IOS推送状态播报:success={}, failure={}", success, failure);
                } catch (InterruptedException e) {
                    log.error("IOS推送守护线程异常:" + e.getMessage());
                }
            }
        });
        iosDaemonThread.start();
        log.info("IOS推送队列状态监控已启动.");
    }

执行推送(实际上是加入到推送队列,由推送队列异步完成推送):

    /**
     * IOS推送
     * @param token
     * @param msg
     * @param data
     */
    private void sendToIos(String token, String msg, Map data) {
        try {
            PushNotificationPayload payload = PushNotificationPayload.complex();
            payload.addAlert(msg);
            // payload.addBadge(1);
            payload.addSound("default");
            if (data != null && !data.isEmpty()) {
                for (Map.Entry map : data.entrySet()) {
                    payload.addCustomDictionary(map.getKey(), map.getValue().toString());
                }
            }
            iosPushQueue.add(payload, token);
            log.info("IOS推送已添加到推送队列");
        } catch (Throwable e) {
            log.error("IOS推送异常", e);
        }
    }

你可能感兴趣的:(SpringCloud 利用Javapns完成IOS APP消息推送)