springboot整合極光推送

轉載請表明出處 https://blog.csdn.net/Amor_Leo/article/details/106851856 謝謝

springboot整合極光推送

準備

官網
先註冊登錄,並創建應用

pom

 <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jsms-client</artifactId>
            <version>1.2.9</version>
        </dependency>
        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jpush-client</artifactId>
            <version>3.3.10</version>
        </dependency>

yml

jpush:
  appKey: xxxx
  masterSecret: xxxxx

工具類

/**
 * @author LHL
 */
@Service
@Getter
@Setter
public class PushServiceImpl implements PushService {

    protected static final Logger LOG = LoggerFactory.getLogger(PushServiceImpl.class);
    
    //極光推送賬戶
    @Value("${jpush.appKey}")
    private String APPKEY;

    @Value("${jpush.masterSecret}")
    private String MASTER_SECRET;
    
    /**
     * 發送自定義推送,由APP端攔截信息後再決定是否創建通知
     *
     * @param title App通知欄標題
     * @param content App通知欄內容(爲了單行顯示全,儘量保持在22個漢字以下)
     * @param extrasMap 額外推送信息(不會顯示在通知欄,傳遞數據用)
     * @param alias 別名數組,設定哪些用戶手機能接收信息(爲空則所有用戶都推送)
     * @return PushResult
     * @author LHL
     */
    @Override
    public PushResult sendCustomPush(String title, String content, Map<String, String> extrasMap, String... alias) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        // 使用NativeHttpClient網絡客戶端,連接網絡的方式,不提供回調函數
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APPKEY, null,
                clientConfig);
        // 設置爲消息推送方式爲僅推送消息,不創建通知欄提醒
        PushPayload payload = buildCustomPushPayload(title, content, extrasMap, alias);
        PushResult result = null;
        try {
            result = jpushClient.sendPush(payload);
            LOG.info("極光推送結果 - " + result+",接收推送的別名列表:" + String.join(",", alias));
            LOG.info("result結果"+result.msg_id+" "+result.sendno);
        } catch (APIConnectionException e) {
            LOG.error("極光推送連接錯誤,請稍後重試 ", e);
            LOG.error("Sendno: " + payload.getSendno());
        } catch (APIRequestException e) {
            LOG.error("極光服務器響應出錯,請修復! ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.info("以下存在不能識別的別名: " + String.join(",", alias));
            LOG.error("Sendno: " + payload.getSendno());
        }
        return result;
    }

    /**
     * 原生方式推送
     *
     * @param title App通知欄標題
     * @param content App通知欄內容(爲了單行顯示全,儘量保持在22個漢字以下)
     * @param extrasMap 額外推送信息(不會顯示在通知欄,傳遞數據用)
     * @param alias 別名數組,設定哪些用戶手機能接收信息(爲空則所有用戶都推送)
     * @author LHL
     */
    @Override
    public PushResult sendPush(String title, String content, Map<String, String> extrasMap, String... alias) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APPKEY);
        // 設置推送方式
        PushPayload payload = buildPushPayload(title, content, extrasMap, alias);
        PushResult result = null;
        try {
            result = jpushClient.sendPush(payload);
            if (null != alias) {
                LOG.info("極光推送結果 - " + result+",接收推送的別名列表:" + String.join(",", alias));
            }
            LOG.info("result結果"+result.msg_id+" "+result.sendno);
        } catch (APIConnectionException e) {
            LOG.error("極光推送連接錯誤,請稍後重試 ", e);
            LOG.error("Sendno: " + payload.getSendno());
        } catch (APIRequestException e) {
            LOG.error("極光服務器響應出錯,請修復! ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.info("以下存在不能識別別名: " + alias);
            LOG.error("Sendno: " + payload.getSendno());
        }
        return result;
    }

    /**
     * 異步請求推送方式
     *
     * @param title 通知欄標題
     * @param content 通知欄內容(爲了單行顯示全,儘量保持在22個漢字以下)
     * @param extrasMap 額外推送信息(不會顯示在通知欄,傳遞數據用)
     * @param alias 需接收的用戶別名數組(爲空則所有用戶都推送) 
     * @see 使用NettyHttpClient,異步接口發送請求,通過回調函數可以獲取推送成功與否情況
     * @author LHL
     */
    @Override
    public void sendPushWithCallback(String title, String content, Map<String, String> extrasMap, String... alias) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        NettyHttpClient client = new NettyHttpClient(
                ServiceHelper.getBasicAuthorization(APPKEY, MASTER_SECRET), null,
                clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
            PushPayload payload = buildPushPayload(title, content, extrasMap, alias);
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    if (200 == responseWrapper.responseCode) {
                        LOG.info("極光推送成功");
                    } else {
                        LOG.info("極光推送失敗,返回結果: " + responseWrapper.responseContent);
                    }
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            // 需要手動關閉Netty請求進程,否則會一直保留
            client.close();
        }

    }

    /**
     * 構建Android和IOS的推送通知對象
     *
     * @return PushPayload
     * @author LHL
     */
    private PushPayload buildPushPayload(String title, String content, Map<String, String> extrasMap, String... alias) {
        if (extrasMap == null || extrasMap.isEmpty()) {
            extrasMap = new HashMap<String, String>();
        }
        // 批量刪除數組中空元素
        String[] newAlias = removeArrayEmptyElement(alias);
        return PushPayload.newBuilder().setPlatform(Platform.android_ios())
                // 別名爲空,全員推送;別名不爲空,按別名推送
                .setAudience((null == newAlias || newAlias.length == 0) ? Audience.all() : Audience.alias(alias))
                .setNotification(Notification.newBuilder().setAlert(content)
                        .addPlatformNotification(AndroidNotification.newBuilder().setTitle(title).addExtras(extrasMap).build())
                        .addPlatformNotification(IosNotification.newBuilder().incrBadge(1).setSound("happy").addExtras(extrasMap).build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(true).build()) //true 生產模式 默認false 開發模式
                .build();
    }

    /**
     * 構建Android和IOS的自定義消息的推送通知對象
     *
     * @return PushPayload
     * @author LHL
     */
    private PushPayload buildCustomPushPayload(String title, String content, Map<String, String> extrasMap,
                                               String... alias) {
        // 批量刪除數組中空元素
        String[] newAlias = removeArrayEmptyElement(alias);
        return PushPayload.newBuilder().setPlatform(Platform.android_ios())
                .setAudience((null == newAlias || newAlias.length == 0) ? Audience.all() : Audience.alias(alias))
                .setMessage(Message.newBuilder().setTitle(title).setMsgContent(content).addExtras(extrasMap).build())
                .build();
    }

    /**
     * 查詢記錄推送成功條數 
     * @param msg_id 在推送返回結果PushResult中保存
     * @author LHL
     */
    @Override
    public void countPush(String msg_id) {
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APPKEY);
        try {
            ReceivedsResult result = jpushClient.getReportReceiveds(msg_id);
            ReceivedsResult.Received received = result.received_list.get(0);
            LOG.debug("Android接受信息:" + received.android_received + "\n IOS端接受信息:" + received.ios_apns_sent);
            LOG.debug("極光推送返回結果 - " + result);
        } catch (APIConnectionException e) {
            LOG.error("極光推送連接錯誤,請稍後重試", e);
        } catch (APIRequestException e) {
            LOG.error("檢查錯誤,並修復推送請求", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
    }


    /**
     * 設置、更新、設備的 tag, alias 信息。
     *
     * @param registrationId 設備的registrationId
     * @param alias          更新設備的別名屬性
     * @param tagsToAdd      添加設備的tag屬性
     * @param tagsToRemove   移除設備的tag屬性
     * @author LHL
     */
    @Override
    public void updateDeviceTagAlias(String registrationId, String alias, Set<String> tagsToAdd, Set<String> tagsToRemove) {
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APPKEY);
        try {
            jpushClient.updateDeviceTagAlias(registrationId, alias, tagsToAdd, tagsToRemove);
            LOG.debug("設置、更新、設備的 tag, alias 信息成功");
        } catch (APIConnectionException e) {
            e.printStackTrace();
            LOG.error("極光推送連接錯誤,請稍後重試", e);
        } catch (APIRequestException e) {
            e.printStackTrace();
            LOG.error("檢查錯誤,並修復推送請求", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    /**
     * 刪除別名中的空元素(需刪除如:null,""," ")
     *
     * @param strArray
     * @return String[]
     * @author LHL
     */
    private String[] removeArrayEmptyElement(String... strArray) {
        if (null == strArray || strArray.length == 0) {
            return null;
        }
        List<String> tempList = Arrays.asList(strArray);
        List<String> strList = new ArrayList<String>();
        Iterator<String> iterator = tempList.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            // 消除空格後再做比較
            if (null != str && !"".equals(str.trim())) {
                strList.add(str);
            }
        }
        // 若僅輸入"",則會將數組長度置爲0
        String[] newStrArray = strList.toArray(new String[strList.size()]);
        return newStrArray;
    }

    // public static void main(String[] args) {
    //     String title = "公告通知";
    //     String content = "測試公告是否發送";
    //     Map<String,String> map = new HashMap<>();
    //     map.put("id","472d788f5edc42829def4c7849abbc3b");
    //     PushServiceImpl p = new PushServiceImpl();
    //     PushResult pushResult = p.sendPush(title, content, map, null);
    //     System.out.println(pushResult.getResponseCode());
    // }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章