1. 程式人生 > >Java NotNoop推送方式例項

Java NotNoop推送方式例項

package com.xxx.pushmsg.service.ios.impl;

import com.xxx.common.constant.CacheConstant;
import com.xxx.common.utils.RedisUtils;
import com.xxx.common.utils.StringUtil;
import com.xxx.pushmsg.service.ios.IosPushMsgService;
import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsDelegate;
import com.notnoop.apns.ApnsService;
import 
com.notnoop.apns.PayloadBuilder; import com.notnoop.exceptions.NetworkIOException; import javapns.notification.transmission.NotificationProgressListener; import javapns.notification.transmission.NotificationThread; import javapns.notification.transmission.NotificationThreads; import org.apache.commons.collections.MapUtils; import
org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.Date; import
java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Service public class IosPushMsgServiceImpl implements IosPushMsgService { private static final Logger log = LoggerFactory.getLogger(IosPushMsgServiceImpl.class); private static final Logger logPush = LoggerFactory.getLogger("push_arrival_rate"); public static final ConcurrentHashMap<Long, Integer> msgStateMap = new ConcurrentHashMap<Long, Integer>(); @Value("${priest.pushmsg.production}")
    //是否是生產環境
    private boolean production;

    @Value("${priest.pushmsg.certificate.file.name}")
    //證書檔案地址
    private String certificateName;

    ApnsService service = null;
    @Resource
private RedisUtils redisUtils;
    //連線池大小
    private int capacity = 20;
    @Resource
private ApnsDelegate delegate;
    @PostConstruct
public void init() {
        String password = "123456"; // 證書密碼
try {
    //初始化服務型別為基本訊息處理型別,並且連線設定為連線池
            service = APNS.newService().withCert(certificateName, password)
                    .asPool(capacity).withDelegate(delegate).withAppleDestination(production).build();
        } catch (Exception e) {
            log.error("Init error Class::IosPushMsgServiceImpl Method::init", e);
        }

    }

   public void stopPush(Long msgId){
      
   }

    public boolean pushOffLineMessageNotnoop(Map<String, String> tokenMessgae, Map<String, Object> mapCustom) {

        if (MapUtils.isEmpty(tokenMessgae)) {
            return true;
        }
        //鈴音,微信等應用實現語音呼叫時使用的方式是將此鈴音設定為30秒的長鈴音,最大限制為30秒。
String sound = "msg.wav";try { this.send(tokenMessgae, null, sound, mapCustom); } catch (Exception ex) { log.error("OffLineMessageNotnoop Multi error Class::IosPushMsgServiceImpl Method::pushOffLineMessageNotnoop Param::message"+ " Param::tokenMessgae:" + tokenMessgae + ",mapCustom:" + mapCustom, ex); } return true; }
    //傳送方法
    private void send(Map<String, String> tokenMessage, String launchImage, String sound, Map<String, Object> mapCustom) {

        try {
            Long nowStart = System.currentTimeMillis();
            Map<String, String> mapCount = this.redisUtils.hGetAll(CacheConstant.CACHE_PREFIX_IOS_GROUP_PUSHMSG_COUNT);
            //傳送訊息
Iterator<String> it = tokenMessage.keySet().iterator();
            while (it.hasNext()) {
                Long nowStart111 = System.currentTimeMillis();
                String token = it.next();
                //因為標準的Token大小為64位,因此如果Token不符合規範則不推
                if (token.length() < 64) {
                    continue;
                }
                String alert = tokenMessage.get(token);
                //構造Payload
                PayloadBuilder payloadBuilder = APNS.newPayload();
                //拼裝訊息
payloadBuilder = payloadBuilder.alertBody(alert);

                if (!StringUtils.isEmpty(launchImage)) {
                    payloadBuilder = payloadBuilder.launchImage(launchImage);
                }
                if (!StringUtils.isEmpty(sound)) {
                    payloadBuilder = payloadBuilder.sound(sound);
                }
                //裁剪訊息
if (payloadBuilder.isTooLong()) {
                    payloadBuilder = payloadBuilder.shrinkBody();
                }
                payloadBuilder = payloadBuilder.forNewsstand();
                //增加額外的資訊
if(null != mapCustom)
                    payloadBuilder.customFields(mapCustom);
                Integer count = 1;
                if (mapCount.containsKey(token)) {
                    String countStr = mapCount.get(token);
                    count = StringUtil.isEmpty(countStr) ? 0 : Integer.valueOf(countStr);
                    if (count < 99) {
                        count = count + 1;
                    } else {
                        count = 99;
                    }
                }
                //設定小紅圈上面的數字
                payloadBuilder.badge(count);
                //組裝成json
String payload = payloadBuilder.build();
                //傳送訊息
                service.push(token, payload, new Date(System.currentTimeMillis() + 1000 * 1000));
                Long nowEnd111 = System.currentTimeMillis();
                //重組訊息體,去除其中的Emoji,否則傳送訊息體會出現問題
                String logContent = StringUtil.filterEmoji(alert).replaceAll("\r","").replaceAll("\n","");
                this.redisUtils.hPut(CacheConstant.CACHE_PREFIX_IOS_GROUP_PUSHMSG_COUNT, token, count);
                StringBuffer sb = new StringBuffer();
                sb.append("{\"token\":");
                sb.append("\"");
                sb.append(token);
                sb.append("\"");
                sb.append(",\"content\":");
                sb.append("{");
                sb.append("\"content\":");
                sb.append("\"");
                sb.append(logContent);
                sb.append("\"");
                sb.append(",\"createTime\":");
                sb.append(nowEnd111);
                sb.append("}");
                sb.append(",\"ret\":");
                sb.append("{\"ret_code\":0}");
                sb.append("}");
                logPush.info(sb.toString());
            }
            Long nowEnd = System.currentTimeMillis();
            log.info("IOSPushMsgSend Cost:" + (nowEnd - nowStart));
        } catch (NetworkIOException e) {
            log.error("Send Multi Error NetworkIOException At Class::IosPushMsgServiceImpl Method::send"
+ " Param::tokenMessage:" + tokenMessage, e);
            if (e.toString().contains("certificate")) {
                //shortMessageService.sendMessage(Long.MAX_VALUE, null, "15001257920", e.toString());
}
        } catch (Exception ex) {
            log.error("Send Multi Error Exception At Class::IosPushMsgServiceImpl Method::send"
+ " Param::tokenMessage:" + tokenMessage, ex);
        } finally  {
        }
    }

   public static final NotificationProgressListener DEBUGGING_PROGRESS_LISTENER = new NotificationProgressListener() {
      public void eventThreadStarted(NotificationThread notificationThread) {
         log.info("EventThreadStarted [EVENT]: thread #" + notificationThread.getThreadNumber() + " started with "
+ " devices beginning at message id #" + notificationThread.getFirstMessageIdentifier()
                    + " At Class::NotificationProgressListener Method::eventThreadStarted" + notificationThread.getFailedNotifications());
      }

      public void eventThreadFinished(NotificationThread thread) {
         log.info("EventThreadFinished [EVENT]: thread #" + thread.getThreadNumber() + " finished: pushed messages #"
+ thread.getFirstMessageIdentifier() + " to " + thread.getLastMessageIdentifier() + " toward " + " devices"
+ " At Class::NotificationProgressListener Method::eventThreadFinished" + thread.getFailedNotifications());
      }

      public void eventConnectionRestarted(NotificationThread thread) {
            log.info("EventConnectionRestarted [EVENT]: connection restarted in thread #" + thread.getThreadNumber()
                    + " because it reached " + thread.getMaxNotificationsPerConnection() + " notifications per connection"
+ " At Class::NotificationProgressListener Method::eventConnectionRestarted" + thread.getFailedNotifications());
      }

      public void eventAllThreadsStarted(NotificationThreads notificationThreads) {
            log.info("EventAllThreadsStarted [EVENT]: all threads started: " + notificationThreads.getThreads().size()
            + " At Class::NotificationProgressListener Method::eventAllThreadsStarted" + notificationThreads.getFailedNotifications());
      }

      public void eventAllThreadsFinished(NotificationThreads notificationThreads) {
            log.info("EventAllThreadsFinished [EVENT]: all threads finished: " + notificationThreads.getThreads().size()
                    + " At Class::NotificationProgressListener Method::eventAllThreadsFinished" + notificationThreads.getFailedNotifications());
      }

      public void eventCriticalException(NotificationThread notificationThread, Exception exception) {
            log.info("EventCriticalException [EVENT]: critical exception occurred: " + exception
                    + " At Class::NotificationProgressListener Method::eventCriticalException" + notificationThread.getFailedNotifications());
        }
   };

    public void setCapacity(int capacity) {
        this.capacity = capacity;
    }

}

相關推薦

Java NotNoop方式例項

package com.xxx.pushmsg.service.ios.impl; import com.xxx.common.constant.CacheConstant; import com.xxx.common.utils.RedisUtils; import com.xxx.common.uti

Android實現方式解決方案

都是 device andro broker dev 常見 剛才 設置 互聯網  本文介紹在Android中實現推送方式的基礎知識及相關解決方案。推送功能在手機開發中應用的場景是越來起來了,不說別的,就我們手機上的新聞客戶端就時不j時的推送過來新的消息,很方便的閱讀最新的新

極光 使用例項 (一)服務端

                原文:http://blog.csdn.net/u014733374/article/detail

個推推模板及方式

四種推送模板 點選通知開啟應用模板 NotificationTemplate • 場景 1:針對沉默使用者,傳送推送訊息,點選訊息欄的通知可直接啟用啟動應用,提升應用的轉化率 點選通知開啟網頁模板 LinkTemplate • 場景 1:推廣促銷活動,使用者點選通知

Servlet3.0 非同步處理 頁面 Comet 例項

本例參考:http://blog.csdn.net/chenxiang0207/article/details/14054681/ 我按照上面博文的思路重新走了一遍 專案結構如下圖 /** * AsyncServlet * * 支援非同步處理的Servlet

【轉載】極光 使用例項 (一)服務端

最近一直在做後臺開發,但心裡還是總惦記著Android,感覺還是Android有意思。正好專案中要用到極光推送,今天抽空來記錄下這兩天的研究成果。         我們知道IOS有自己的推送服務,但很遺憾Android沒有原生的推送服務,現在有很多第三方的推送服務,比如個推、極光、亞馬遜、百度雲、聚能等。今天

Java-極光

本文寫的是極光推送JAVA後臺程式碼,小弟第一次接觸推送,特此謹記,以備其他同道中人和自己日後之需 首先,POM檔案,以下是極光需要的所有jar包,千萬要記得極光需要slf4j的jar包,必須引入slf4j <dependency>

java伺服器訊息技術

其實有很多種方式實現伺服器推送,它們各有各的優缺點: 1.傳統輪詢:此方法是利用 HTML 裡面 meta 標籤的重新整理功能,在一定時間間隔後進行頁面的轉載,以此迴圈往復。它的最大缺點就是頁面刷性給人帶來的體驗很差,而且伺服器的壓力也會比較大。 2.Ajax 輪詢:非同步響應機制,即通過不間斷的客戶端 A

Java後臺伺服器實現極光的兩種實現方式

Java後臺實現極光推送有兩種方式,一種是使用極光推送官方提供的推送請求API:https://api.jpush.cn/v3/push,另一種則是使用官方提供的第三方Java SDK,這裡先進行第一種方式推送的實現程式碼:第一種推送方式:極光官方提供的推送請求APIimpo

comet4j java服務端訊息到web頁面例項

官網:http://code.google.com/p/comet4j/ 準備工作 下載服務端jar檔案 Comet4J目前僅支援Tomcat6、7版本,根據您所使用的Tomcat版本下載【comet4jtomcat6.jar】或【comet4j-tomcat7.

郵件 Java代碼

cati pass protected esc 郵件 .text extend *** pwd package mail; /** * @Description:郵件信息類 * * @ClassName: SimpleMail */ public

對接第三方平臺JAVA接口問題和解決

處理 end isp var created esc 再看 名稱 mba 前言 本節所講為實際項目中與第三方對接出現的問題最後還是靠老大解決了問題以此作為備忘錄,本篇分為三小節,一小節解析Java加密接口數據,二小節解析XML文件需註意問題,最後一節則是請求Java So

愛創課堂每日一題第五十五天- WEB應用從服務器主動Data到客戶端有那些方式

前端 前端學習 前端入門Javascript數據推送Commet:基於HTTP長連接的服務器推送技術基於WebSocket的推送方案SSE(Server-Send Event):服務器推送數據新方式愛創課堂每日一題第五十五天- WEB應用從服務器主動推送Data到客戶端有那些方式?

Java 消息------GoEasy實現服務端和web端

subscribe rip world 查詢 start easy 需要 註冊 註意 項目中需要消息推送,又想較低開發成本,具體需求:角色用戶在後臺管理頁面發布一個消息,所有用這個系統的用戶無論在哪個頁面都能及時收到他發布的消息,後來我在網上查詢到了一個第三方的免費推送服務

微信公眾號 模板消息 定時 java

quest 微信 cat 2個 使用權 output 行業 交流 set 前提:業務需要,要做一個關於月報的微信消息推送。即每個月定時自動發送一條消息 給關註 公眾號的人 用的是 公眾號的測試賬號(實際開發需要認證的公眾號) 微信官網的 模板消息接口規則: 1、所有服務號

AndroidStudio離線打包MUI集成JPush極光並在java後端管理

覆蓋 如果 dep record tco mat resource 靜態 pkg 1.AndroidStudio離線打包MUI   如何離線打包請參看上篇隨筆《AndroidStudio離線打包MUI》 2.集成極光推送   官方文檔:https://docs.jig

java集成jpush實現客戶端

step eclips 著作權 步驟 isn new args set oid 代碼地址如下:http://www.demodashi.com/demo/13700.html 前言 java 集成jpush 實現客戶端推送 一、準備工作 開發環境: jdk1.6 Ecl

3行java代碼實現百度站長主動12

收錄 工具 eboot ont 提交 pan 下載 工具類 百度收錄 介紹 當網站新增了一個網頁之後,此時這個網頁是不能夠立馬被百度收錄的,如果想以最快的速度被百度收錄則可以使用百度站長工具中的連接提交來主動向百度提交,讓百度收錄該網頁。 本文演示java使

JAVA多執行緒(四) Executor併發框架向RabbitMQ訊息

github程式碼地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo  假設一個需求使用者點選某個頁面,我們後臺需要向MQ推送信資訊 1,模擬的MQ服務,我這邊使用RabbitMQ (關於MQ 傳送和監聽訊息可以

Java開發微信小程式(三)用小程式給使用者服務訊息

第三篇 用小程式給使用者推送服務訊息 1.小程式登入獲取,小程式的openId和unionId。 2.獲取並解密小程式的加密資訊包括使用者和手機資訊。 3.用小程式給使用者推送服務訊息。 4.給繫結小程式而且又關注微信公眾號的使用者推送公眾號訊息。 小程式訊息推送機制有