Spring boot集成極光推送工具類

前言

首先,歡迎大家前來參觀我的博文!今天我給大家帶來的是“極光推送”在服務端的集成。推送第三方有很多,類似信鴿、友盟、阿里推送等。廢話不多說,下面進入正題。

引入POM相關包

在項目中引入以下三個包:

<!-- 極光推送 -->
<dependency>
    <groupId>cn.jpush.api</groupId>
    <artifactId>jpush-client</artifactId>
    <version>3.4.3</version>
</dependency>
<!-- 解析yml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<!-- 阿里巴巴的對象與json互轉等工具類,建議最新版,60版之前有出現高危漏洞 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.67</version>
</dependency>

yml文件配置

# 極光推送 (true測試環境,false正式環境)
jpush:
  environment: true
  appKey: d3fa5dfb20234c72ea23e1d6
  masterSecret: 7b111536095bb374b9086040

解析yml轉對象

在IDEA中我引入了lombok插件,這個自行配置一下:

package com.xx.xx.jpush;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * [ 極光推送配置 ]
 *
 * @author Love丶TG
 * @version 1.0.0
 * @create 2020 年 03 月 25 日 9:57
 */
@Component
@Data
@ConfigurationProperties(prefix = "jpush")
public class JPushParam {
    private Boolean environment;
    private String appKey;
    private String masterSecret;
}

推送工具類

下面代碼完成靠你自己去理解了,靜默推送(穿透推送)就把setNotification移除,不配置setNotification就行了,安卓和IOS一樣;還有要注意以下是全平臺推送、全安卓推送、全IOS推送,若要單推,就要靠自己去改爲註冊ID或者別名進行推送處理了。實在不懂,你可以考慮留言。(我第一時間看到一定第一時間給你回覆😁 老師常教導我:天下文章一大抄,看你會抄不會抄。)

package com.xx.xx.jpush;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * [ 推送工具類 ]
 *
 * @author Love丶TG
 * @version 1.0.0
 * @create 2020 年 03 月 25 日 10:18
 */
@Slf4j
@Component
public class JPushUtils {

    @Autowired
    private JPushParam jPush;

    public static JPushUtils jPushUtils;

    @PostConstruct
    public void init() {
        jPushUtils = this;
    }

    /**
     * 獲取JPushClient實例
     *
     * @return
     */
    private static JPushClient getJPushClient() {
        JPushClient jPushClient = new JPushClient(jPushUtils.jPush.getMasterSecret(), jPushUtils.jPush.getAppKey());
        return jPushClient;
    }

    /**
     * 發送給所有用戶
     *
     * @param notification_title 通知內容標題
     * @param msg_title          消息內容標題
     * @param msg_content        消息內容
     * @param extrasparam        擴展字段
     * @return false推送失敗,true推送成功
     */
    public static boolean sendToAll(String notification_title, String msg_title, String msg_content, String extrasparam) {
        boolean result = false;
        try {
            PushPayload pushPayload = PushPayload.newBuilder()
                    .setPlatform(Platform.android_ios())
                    .setAudience(Audience.all())
                    // .setAudience(Audience.alias(alias))     // List<String> alias 設備標識
                    .setNotification(Notification.newBuilder()
                            .setAlert(msg_content)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setAlert(msg_content)
                                    .setTitle(notification_title)
                                    //此字段爲透傳字段,不會顯示在通知欄。用戶可以通過此字段來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
                                    .addExtra("url", extrasparam)
                                    .build()
                            )
                            .addPlatformNotification(IosNotification.newBuilder()
                                    //傳一個IosAlert對象,指定apns title、title、subtitle等
                                    .setAlert(msg_content)
                                    //直接傳alert
                                    //此項是指定此推送的badge自動加1
                                    .incrBadge(1)
                                    //此字段的值default表示系統默認聲音;傳sound.caf表示此推送以項目裏面打包的sound.caf聲音來提醒,
                                    // 如果系統沒有此音頻則以系統默認聲音提醒;此字段如果傳空字符串,iOS9及以上的系統是無聲音提醒,以下的系統是默認聲音
                                    .setSound("sound.caf")
                                    //此字段爲透傳字段,不會顯示在通知欄。用戶可以通過此字段來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
                                    .addExtra("url", extrasparam)
                                    //此項說明此推送是一個background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
                                    // .setContentAvailable(true)

                                    .build()
                            )
                            .build()
                    )
                    //Platform指定了哪些平臺就會像指定平臺中符合推送條件的設備進行推送。 jpush的自定義消息,
                    // sdk默認不做任何處理,不會有通知提示。建議看文檔http://docs.jpush.io/guideline/faq/的
                    // [通知與自定義消息有什麼區別?]瞭解通知和自定義消息的區別
                    .setMessage(Message.newBuilder()
                            .setMsgContent(msg_content)
                            .setTitle(msg_title)
                            .addExtra("url", extrasparam)
                            .build())

                    .setOptions(Options.newBuilder()
                            //此字段的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義消息無意義
                            .setApnsProduction(jPushUtils.jPush.getEnvironment())
                            //此字段是給開發者自己給推送編號,方便推送者分辨推送記錄
                            .setSendno(1)
                            //此字段的值是用來指定本推送的離線保存時長,如果不傳此字段則默認保存一天,最多指定保留十天,單位爲秒
                            .setTimeToLive(86400)
                            .build()
                    )
                    .build();
            PushResult pushResult = getJPushClient().sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                result = true;
            }
            log.info("[極光推送]PushResult result is " + pushResult);
        } catch (APIConnectionException e) {
            log.error("[極光推送]Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("[極光推送]Error response from JPush server. Should review and fix it. ", e);
            log.info("[極光推送]HTTP Status: " + e.getStatus());
            log.info("[極光推送]Error Code: " + e.getErrorCode());
            log.info("[極光推送]Error Message: " + e.getErrorMessage());
        }

        return result;
    }

    /**
     * 發送給所有安卓用戶
     *
     * @param notification_title 通知內容標題
     * @param msg_title          消息內容標題
     * @param msg_content        消息內容
     * @param extrasparam        擴展字段
     * @return false推送失敗,true推送成功
     */
    public static boolean sendToAllAndroid(String notification_title, String msg_title, String msg_content, String extrasparam) {
        boolean result = false;
        try {
            // (透傳消息android 也不用傳Notification)
            PushPayload pushPayload = PushPayload.newBuilder()
                    //指定要推送的平臺,all代表當前應用配置了的所有平臺,也可以傳android等具體平臺
                    .setPlatform(Platform.android())
                    //指定推送的接收對象,all代表所有人,也可以指定已經設置成功的tag或alias或該應應用客戶端調用接口獲取到的registration id
                    .setAudience(Audience.all())
                    // .setAudience(Audience.registrationId(notice.getRegistrationId()))
                    //jpush的通知,android的由jpush直接下發,iOS的由apns服務器下發,Winphone的由mpns下發
                    .setNotification(Notification.newBuilder()
                            //指定當前推送的android通知
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setAlert(msg_content)
                                    .setTitle(notification_title)
                                    //此字段爲透傳字段,不會顯示在通知欄。用戶可以通過此字段來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
                                    .addExtra("url", extrasparam)
                                    .build())
                            .build()
                    )
                    //Platform指定了哪些平臺就會像指定平臺中符合推送條件的設備進行推送。 jpush的自定義消息,
                    // sdk默認不做任何處理,不會有通知提示。建議看文檔http://docs.jpush.io/guideline/faq/的
                    // [通知與自定義消息有什麼區別?]瞭解通知和自定義消息的區別
                    .setMessage(Message.newBuilder()
                            .setMsgContent(msg_content)
                            .setTitle(msg_title)
                            .addExtra("url", extrasparam)
                            .build())

                    .setOptions(Options.newBuilder()
                            //此字段的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義消息無意義
                            .setApnsProduction(jPushUtils.jPush.getEnvironment())
                            //此字段是給開發者自己給推送編號,方便推送者分辨推送記錄
                            .setSendno(1)
                            //此字段的值是用來指定本推送的離線保存時長,如果不傳此字段則默認保存一天,最多指定保留十天,單位爲秒
                            .setTimeToLive(86400)
                            .build())
                    .build();
            PushResult pushResult = getJPushClient().sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                result = true;
            }
            log.info("[極光推送]PushResult result is " + pushResult);
        } catch (APIConnectionException e) {
            log.error("[極光推送]Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("[極光推送]Error response from JPush server. Should review and fix it. ", e);
            log.info("[極光推送]HTTP Status: " + e.getStatus());
            log.info("[極光推送]Error Code: " + e.getErrorCode());
            log.info("[極光推送]Error Message: " + e.getErrorMessage());
        }

        return result;
    }

    /**
     * 發送給所有IOS用戶
     *
     * @param notification_title 通知內容標題
     * @param msg_title          消息內容標題
     * @param msg_content        消息內容
     * @param extrasparam        擴展字段
     * @return false推送失敗,true推送成功
     */
    public static boolean sendToAllIos(String notification_title, String msg_title, String msg_content, String extrasparam) {
        boolean result = false;
        try {
            // IosNotification.Builder builder = IosNotification.newBuilder()
            //         .setAlert(IosAlert.newBuilder().setTitleAndBody(msg_title, null, msg_content).build())
            //         .addExtras(extrasparam);
            //  if (!JpushNotice.PASSTHROUGH.equals(notice.getContentType())) {
            //     builder = builder.incrBadge(1);
            // }
            //(透傳消息ios不用配置setNotification屬性)
            PushPayload pushPayload = PushPayload.newBuilder()
                    //指定要推送的平臺,all代表當前應用配置了的所有平臺,也可以傳android等具體平臺
                    .setPlatform(Platform.ios())
                    //指定推送的接收對象,all代表所有人,也可以指定已經設置成功的tag或alias或該應應用客戶端調用接口獲取到的registration id
                    .setAudience(Audience.all())
                    // .setAudience(Audience.registrationId(notice.getRegistrationId()))
                    //jpush的通知,android的由jpush直接下發,iOS的由apns服務器下發,Winphone的由mpns下發
                    .setNotification(Notification.newBuilder()
                            //指定當前推送的android通知
                            // .addPlatformNotification(builder.build()).build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    //傳一個IosAlert對象,指定apns title、title、subtitle等
                                    .setAlert(msg_content)
                                    //直接傳alert
                                    //此項是指定此推送的badge自動加1
                                    .incrBadge(1)
                                    // .setBadge(+1)
                                    //此字段的值default表示系統默認聲音;傳sound.caf表示此推送以項目裏面打包的sound.caf聲音來提醒,
                                    // 如果系統沒有此音頻則以系統默認聲音提醒;此字段如果傳空字符串,iOS9及以上的系統是無聲音提醒,以下的系統是默認聲音
                                    .setSound("sound.caf")
                                    // .setSound("happy")
                                    //此字段爲透傳字段,不會顯示在通知欄。用戶可以通過此字段來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
                                    .addExtra("url", extrasparam)
                                    //此項說明此推送是一個background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
                                    // .setContentAvailable(true)

                                    .build())
                            .build()
                    )
                    //Platform指定了哪些平臺就會像指定平臺中符合推送條件的設備進行推送。 jpush的自定義消息,
                    // sdk默認不做任何處理,不會有通知提示。建議看文檔http://docs.jpush.io/guideline/faq/的
                    // [通知與自定義消息有什麼區別?]瞭解通知和自定義消息的區別
                    .setMessage(Message.newBuilder()
                            .setMsgContent(msg_content)
                            .setTitle(msg_title)
                            .addExtra("url", extrasparam)
                            .build())

                    .setOptions(Options.newBuilder()
                            //此字段的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義消息無意義
                            .setApnsProduction(jPushUtils.jPush.getEnvironment())
                            //此字段是給開發者自己給推送編號,方便推送者分辨推送記錄
                            .setSendno(1)
                            //此字段的值是用來指定本推送的離線保存時長,如果不傳此字段則默認保存一天,最多指定保留十天,單位爲秒
                            .setTimeToLive(86400)
                            .build())
                    .build();
            PushResult pushResult = getJPushClient().sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                result = true;
            }
            log.info("[極光推送]PushResult result is " + pushResult);
        } catch (APIConnectionException e) {
            log.error("[極光推送]Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("[極光推送]Error response from JPush server. Should review and fix it. ", e);
            log.info("[極光推送]HTTP Status: " + e.getStatus());
            log.info("[極光推送]Error Code: " + e.getErrorCode());
            log.info("[極光推送]Error Message: " + e.getErrorMessage());
        }

        return result;
    }
}

推送Test類

以下代碼爲測試類中調試的部分代碼(最後一個字段就是隱式封裝的傳遞json串):

		PushVO pushVO = new PushVO();
        pushVO.setId(1L);
        pushVO.setUsername("tty");
        pushVO.setContent("我是Love丶TG");
        System.err.println(JPushUtils.sendToAllAndroid("通知標題", "消息標題", "通知|消息內容", JSON.toJSONString(pushVO)));

以上就完成了極光推送服務工具類,覺得不錯的遊客,麻煩加個關注,讓我多個粉絲,博主我萬分感謝!!!

(*注:以後文章僅粉絲可見😂)

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