Spring Boot 是目前非常流行的Java Web框架之一,它提供了很多便捷的开发方式和功能,其中集成消息推送是比较常见的需求,本篇博客将介绍如何在 Spring Boot 中集成个推和 UniPush 两种消息推送方式。

Spring Boot 集成 个推 和 UniPush 两种消息推送方式_android

一、集成个推

1. 注册个推账号

首先需要注册个推账号并创建应用,获取到AppID、AppKey和MasterSecret,这些参数在后续的开发中会用到;需要注意的是之前的老板本已经没有在维护了,现在需要引入最新的依赖包。

个推消息推送 参考文档

2. 引入个推SDK

在pom.xml中添加个推SDK的依赖:

<!-- https://mvnrepository.com/artifact/com.getui.push/restful-sdk -->
<dependency>
    <groupId>com.getui.push</groupId>
    <artifactId>restful-sdk</artifactId>
    <version>1.0.0.11</version>
</dependency>

3. 配置个推参数

在application.properties中配置个推相关参数:

# 个推相关配置
getui.appId=你的AppID
getui.appKey=你的AppKey
getui.appSecret=你的AppSecret
getui.masterSecret=你的MasterSecret
getui.baseUrl=https://restapi.getui.com/v2/

# 个推相关配置
getui:
	appId: 你的AppID
	appKey: 你的AppKey
	appSecret: 你的AppSecret
	masterSecret: 你的MasterSecret    
	# Url前缀
	baseUrl: https://restapi.getui.com/v2/

4. 编写个推配置类

/**
 * 个推配置类
 **/
@Configuration
public class GeTuiConfig {
    @Value("${getui.baseUrl}")
    private String baseUrl;

    @Value("${getui.appId}")
    private String appId;

    @Value("${getui.appKey}")
    private String appKey;

    @Value("${getui.appSecret}")
    private String appSecret;

    @Value("${getui.masterSecret}")
    private String masterSecret;

    @Bean(name = "myPushApi")
    public PushApi pushApi() {
        // 设置httpClient最大连接数,当并发较大时建议调大此参数。或者启动参数加上 -Dhttp.maxConnections=200
        System.setProperty("http.maxConnections", "200");
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        //填写应用配置
        apiConfiguration.setAppId(appId);
        apiConfiguration.setAppKey(appKey);
        apiConfiguration.setMasterSecret(masterSecret);
        // 接口调用前缀,请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
        apiConfiguration.setDomain(baseUrl);
        // 实例化ApiHelper对象,用于创建接口对象
        ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
        // 创建对象,建议复用。目前有PushApi、StatisticApi、UserApi
        return apiHelper.creatApi(PushApi.class);
    }
}

5. 编写个推推送工具类

推送工具的代码如下:

@Slf4j
@Component
public class GeTuiUtils {

    @Resource(name = "myPushApi")
    private PushApi myPushApi;

    /**
     * 单点推送(离线不推送)
     *
     * @param cid     目标
     * @param title   标题
     * @param content 内容
     */
    public void pushMsg(String cid, String title, String content) {
        //根据cid进行单推
        PushDTO<Audience> pushDTO = new PushDTO<>();
        // 设置推送参数
        pushDTO.setRequestId(IdUtil.fastSimpleUUID());
        // 个推推送消息参数
        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);
        /** 带跳转url*/
//        GTNotification notification = new GTNotification();
//        pushMessage.setNotification(notification);
//        notification.setTitle(title + new Date());
//        notification.setBody(content);
//        notification.setClickType("url");
//        notification.setUrl("https://www.baidu.com");// 跳转地址
        /** 不带跳转url*/
        pushMessage.setTransmission(" {title:\"" + title + "\",content:\"" + content + "\",payload:\"自定义数据\"}");
        pushDTO.setPushMessage(pushMessage);
        // 设置接收人信息
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
        audience.addCid(cid);
        // 进行cid单推
        ApiResult<Map<String, Map<String, String>>> apiResult = myPushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            // success
            System.out.println(apiResult.getData());
        } else {
            // failed
            System.out.println("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }

    /**
     * 推送给多个
     *
     * @param cids    目标集
     * @param title   标题
     * @param content 内容
     */
    public void pushMsg(List<String> cids, String title, String content) {
        List<PushDTO<Audience>> list = new ArrayList<>(cids.size());
        cids.forEach(cid -> {
            PushDTO<Audience> pushDTO = new PushDTO<>();
            // 唯一标识
            pushDTO.setRequestId(IdUtil.fastSimpleUUID());
            // 消息内容
            PushMessage pushMessage = new PushMessage();
            pushMessage.setNetworkType(0);
            // 透传消息内容
            pushMessage.setTransmission(" {title:\"" + title + "\",content:\"" + content + "\",payload:\"自定义数据\"}");
            pushDTO.setPushMessage(pushMessage);
            // 消息接受人
            Audience audience = new Audience();
            audience.addCid(cid);
            pushDTO.setAudience(audience);
            list.add(pushDTO);
        });
        PushBatchDTO pushBatchDTO = new PushBatchDTO();
        pushBatchDTO.setAsync(true);
        pushBatchDTO.setMsgList(list);
        ApiResult<Map<String, Map<String, String>>> mapApiResult = myPushApi.pushBatchByCid(pushBatchDTO);
        if (mapApiResult.isSuccess()) {
            // success
            System.out.println(mapApiResult.getData());
        } else {
            // failed
            System.out.println("code:" + mapApiResult.getCode() + ", msg: " + mapApiResult.getMsg());
        }
    }

    /**
     * 消息推送(离线推送)
     *
     * @param cid     目标
     * @param title   标题
     * @param content 内容
     */
    public void offlinePushMsg(String cid, String title, String content) {
        //根据cid进行单推
        PushDTO<Audience> pushDTO = new PushDTO<>();
        // 设置推送参数
        pushDTO.setRequestId(System.currentTimeMillis() + "");//requestid需要每次变化唯一
        //配置推送条件
        // 1: 表示该消息在用户在线时推送个推通道,用户离线时推送厂商通道;
        // 2: 表示该消息只通过厂商通道策略下发,不考虑用户是否在线;
        // 3: 表示该消息只通过个推通道下发,不考虑用户是否在线;
        // 4: 表示该消息优先从厂商通道下发,若消息内容在厂商通道代发失败后会从个推通道下发。
        Strategy strategy = new Strategy();
        strategy.setDef(1);
        Settings settings = new Settings();
        settings.setStrategy(strategy);
        pushDTO.setSettings(settings);
        settings.setTtl(3600000);//消息有效期,走厂商消息需要设置该值
        //推送苹果离线通知标题内容
        Alert alert = new Alert();
        alert.setTitle(title);//苹果离线通知栏标题
        alert.setBody(content);//苹果离线通知栏内容
        Aps aps = new Aps();
        //1表示静默推送(无通知栏消息),静默推送时不需要填写其他参数。
        //苹果建议1小时最多推送3条静默消息
        aps.setContentAvailable(0);
        aps.setSound("default");
        aps.setAlert(alert);
        IosDTO iosDTO = new IosDTO();
        iosDTO.setAps(aps);
        iosDTO.setType("notify");
        PushChannel pushChannel = new PushChannel();
        pushChannel.setIos(iosDTO);
        //安卓离线厂商通道推送消息体
        PushChannel pushChannel1 = new PushChannel();
        AndroidDTO androidDTO = new AndroidDTO();
        Ups ups = new Ups();
        ThirdNotification notification1 = new ThirdNotification();
        ups.setNotification(notification1);
        notification1.setTitle(title);//安卓离线展示的标题
        notification1.setBody(content);//安卓离线展示的内容
        notification1.setClickType("intent");
        notification1.setIntent("intent:#Intent;launchFlags=0x04000000;action=android.intent.action.oppopush;component=io.dcloud.HBuilder/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=测试标题;S.content=测试内容;S.payload=test;end");
        //各厂商自有功能单项设置
        //ups.addOption("HW", "/message/android/notification/badge/class", "io.dcloud.PandoraEntry ");
        //ups.addOption("HW", "/message/android/notification/badge/add_num", 1);
        //ups.addOption("HW", "/message/android/notification/importance", "HIGH");
        //ups.addOption("VV","classification",1);
        androidDTO.setUps(ups);
        pushChannel1.setAndroid(androidDTO);
        pushDTO.setPushChannel(pushChannel1);

        // PushMessage在线走个推通道才会起作用的消息体
        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);
        pushMessage.setTransmission(" {title:\"" + title + "\",content:\"" + content + "\",payload:\"自定义数据\"}");
        // 设置接收人信息
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
        audience.addCid(cid);// cid
        // 进行cid单推
        ApiResult<Map<String, Map<String, String>>> apiResult = myPushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            // success
            System.out.println(apiResult.getData());
        } else {
            // failed
            System.out.println("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }

    /**
     * 官方api案例
     */
    public void offlinePushMsg1() {
        //根据cid进行单推
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        // 设置推送参数
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        /**** 设置个推通道参数 *****/
        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);
        GTNotification notification = new GTNotification();
        pushMessage.setNotification(notification);
        notification.setTitle("个title");
        notification.setBody("个body");
        notification.setClickType("url");
        notification.setUrl("https://www.getui.com");
        /**** 设置个推通道参数,更多参数请查看文档或对象源码 *****/

        /**** 设置厂商相关参数 ****/
        PushChannel pushChannel = new PushChannel();
        pushDTO.setPushChannel(pushChannel);
        /*配置安卓厂商参数*/
        AndroidDTO androidDTO = new AndroidDTO();
        pushChannel.setAndroid(androidDTO);
        Ups ups = new Ups();
        androidDTO.setUps(ups);
        ThirdNotification thirdNotification = new ThirdNotification();
        ups.setNotification(thirdNotification);
        thirdNotification.setTitle("厂商title");
        thirdNotification.setBody("厂商body");
        thirdNotification.setClickType("url");
        thirdNotification.setUrl("https://www.getui.com");
        // 两条消息的notify_id相同,新的消息会覆盖老的消息,取值范围:0-2147483647
        // thirdNotification.setNotifyId("11177");
        /*配置安卓厂商参数结束,更多参数请查看文档或对象源码*/

        /*设置ios厂商参数*/
        IosDTO iosDTO = new IosDTO();
        pushChannel.setIos(iosDTO);
        // 相同的collapseId会覆盖之前的消息
        iosDTO.setApnsCollapseId("xxx");
        Aps aps = new Aps();
        iosDTO.setAps(aps);
        Alert alert = new Alert();
        aps.setAlert(alert);
        alert.setTitle("通知消息标题");
        alert.setBody("通知消息内容");
        /*设置ios厂商参数结束,更多参数请查看文档或对象源码*/

        /*设置接收人信息*/
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
        audience.addCid("xxx");
        /*设置接收人信息结束*/
        /**** 设置厂商相关参数,更多参数请查看文档或对象源码 ****/

        // 进行cid单推
        ApiResult<Map<String, Map<String, String>>> apiResult = myPushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            // success
            System.out.println(apiResult.getData());
        } else {
            // failed
            System.out.println("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }
}

调用推送代码:

@Resource
    private GeTuiUtils geTuiUtils;

    public void pushOne(String cid, String title, String content) {
        geTuiUtils.pushMsg(cid, title, content);
    }

二、集成UniPush

1. 注册UniPush账号

首先需要注册UniPush账号并创建应用,获取到AppKey和AppSecret,这些参数在后续的开发中会用到。

UniPush

2. 引入UniPush SDK

在pom.xml中添加UniPush SDK的依赖:

<dependency>
    <groupId>com.github.yunai</groupId>
    <artifactId>yunpian-unipush-sdk</artifactId>
    <version>2.2.2</version>
</dependency>

3. 配置UniPush参数

在application.properties中配置UniPush相关参数:

# UniPush相关配置
unipush.appkey=你的AppKey
unipush.appsecret=你的AppSecret
unipush.host=https://api.unipush.me/rest/

# UniPush相关配置
unipush:
    appkey: 你的AppKey
    appsecret: 你的AppSecret
    host: https://api.unipush.me/rest/

4. 编写UniPush推送代码

推送消息的代码如下:

@Service
public class UniPushService {

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

    @Value("${unipush.appkey}")
    private String appKey;

    @Value("${unipush.appsecret}")
    private String appSecret;

    @Value("${unipush.host}")
    private String host;

    public void pushMessage(String cid, String message) {
        try {
	        //   二选一
            YunpianUniPushClient client = new YunpianUniPushClient(appKey, appSecret, host);
            PushApi api = client.getPushApi();
            PushReq req = new PushReq();
            req.setCid(cid);
            req.setMsg(message);
            PushResult result = api.push(req);

			// 二选一
	        // 创建UniPush推送客户端
	        UniPushClient push = new UniPushClient(appKey, appSecret, host);
	        // 创建消息推送对象
	        PushMessage msg = new PushMessage();
	        msg.setCid(cid);
	        msg.setMessage(message);
	        msg.setTimestamp(System.currentTimeMillis());
	        // 发送消息推送请求
	        PushResponse response = push.push(msg);
            logger.info("UniPush消息推送结果:{}", result);
        } catch (Exception e) {
            logger.error("UniPush消息推送异常:", e);
        }
    }
}

调用推送代码:

@Autowired
private UniPushService uniPushService;

public void pushMessage(String cid, String message) {
    uniPushService.pushMessage(cid, message);
}

三、总结

以上就是在 Spring Boot 中集成个推和 UniPush 的步骤,需要注意的是在使用个推和 UniPush 的时候需要有相应的账号和应用,并且在推送消息时需要传入对应的cid和message参数,以达到正确推送消息的目的。