java对接极光推送Rest API 实现消息推送

java对接极光推送Rest API 实现消息推送

最近的一个项目需求是根据小区id给APP用户推送消息,我是使用别名来实现的。

需要的 maven:

 <!--极光推送API-->
		<dependency>
			<groupId>cn.jpush.api</groupId>
			<artifactId>jpush-client</artifactId>
			<version>3.3.10</version>
		</dependency>
		<dependency>
			<groupId>org.msgpack</groupId>
			<artifactId>msgpack</artifactId>
			<version>0.6.12</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

首先,定义一个JPushData消息类,包括标题,内容,别名等字段,(标签我没有用到)。

@Data
public class JPushData {

    private Integer id;
    
    private String title;  //推送标题

    private String content;  //推送内容

    private String tag;  //推送分类标签

    private List<String> alias;  //  别名
}

关于别名,这个是客户端注册到极光的,需要与安卓与ios商量好别名的设置规则,只需要根据条件(我这里是小区id)查询用户的别名。

然后写了一个推送消息的工具类,在消息推送Controller里面调用该工具类的sendClient方法就可以啦,buyerAppKey 和 buyerMasterSecret 是极光后台获取的,需要填写自己的哦:

package com.zh.common.management.utils;

import cn.jiguang.common.ClientConfig;
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.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import com.zh.common.management.common.entity.JPushData;
import org.apache.log4j.Logger;
import java.util.Map;


public class JPushManager {

    // 日志
    private static final Logger log = Logger.getLogger(JPushManager.class);
    // 推送客户端
    private static JPushClient buyerJpushClient = null;

    static {
        String buyerAppKey = null; // 推送app key
        String buyerMasterSecret = null;// 推送app主密码
        // int buyerMaxRetryTimes = 3;// 推送最大重发次数

        buyerAppKey = "9c85dd79f9367768e0abd6a1";
        buyerMasterSecret = "2f8c56765435671cbe1d90c01";
        ClientConfig config = ClientConfig.getInstance();
        config.setMaxRetryTimes(5);
        config.setApnsProduction(false); 	// development env
        config.setTimeToLive(60 * 60 * 24);
        buyerJpushClient = new JPushClient(buyerMasterSecret, buyerAppKey,
                null, config);
    }

    public static String sendClient(JPushData pushData,
                                  Map<String, String> extraMap) {
        PushPayload payload = sendMsgByAlias(pushData);
        String m="400";
        try {
            PushResult result  = buyerJpushClient.sendPush(payload);
            log.info("Got result - " + result);
             m="200";
        } catch (APIConnectionException e) {
            log.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }
     return m;
    }

    public static PushPayload sendMsgByAlias(JPushData pushData){
        Message message = Message.newBuilder()
                .setMsgContent(pushData.getContent())
                .setTitle(pushData.getTitle())
                .setContentType(pushData.getTag())
                .build();
        return PushPayload.newBuilder()
				.setPlatform(Platform.all())
				.setAudience(Audience.alias(pushData.getAlias()))
				//通知
				//.setNotification(Notification.alert())
				//使用自定义消息推送
				.setMessage(message)
				.build();
    }

}

最后,前端把消息的标题,内容,要推送的小区id传过来,调用上面工具类的sendClient方法即可。
List alias 是我用来存放别名的,客户端注册别名时使用“wuliu_”+user_id,所以我这里就通过小区id查询到所有用户的user_id在前面加上“wuliu_”。

 @PostMapping
    @ApiOperation("增加消息")
    public R<Boolean> add(Message message) {
        message.setTenantId(getTenantId());
        boolean n=messageService.insert(message);
        JPushData jPushData=new JPushData();
        BeanUtils.copyProperties(message,jPushData);
        List<String> alias=new ArrayList<>();
        List<Owner> list=ownerService.selectList(new EntityWrapper<Owner>().eq("community_id",message.getCommunityId()).eq("del_flag",0));
        for(Owner owner :list){
            if(owner.getUserId()!=null) {
                alias.add("wuliu_"+owner.getUserId());
            }
        }
        jPushData.setAlias(alias);
        Map map=new HashMap();
       if(JPushManager.sendClient(jPushData,map)=="200"){//推送成功 修改状态1
           Message m=new Message();
           m.setId(message.getId());
           m.setStatus("1");
           messageService.updateById(m);
       }
        return new R<>(n);
    }

有问题希望大家提出,一起交流~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值