一、引入核心包
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.7.3</version>
</dependency>
二、整理工具包
package com.jddz.cloud.xxx.util;
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.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 cn.jpush.api.schedule.ScheduleListResult;
import cn.jpush.api.schedule.ScheduleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class JPushUtil {
protected static final Logger LOG = LoggerFactory.getLogger(JPushUtil.class);
// App私有信息
private static final String APP_KEY = xxxxxxx;
private static final String MASTER_SECRET = xxxxxx;
private static JPushUtil instance = null;
private ClientConfig clientConfig;
private JPushClient jpushClient;
private JPushUtil() {
clientConfig = ClientConfig.getInstance();
jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
}
public static JPushUtil getInstance() {
if (instance == null) {
synchronized (JPushUtil.class) {
if (instance == null) {
instance = new JPushUtil();
}
}
}
return instance;
}
/**
* 构建消息对象
*
* @param messageVo
* @return
*/
private static PushPayload buildPushObject_android_and_ios(JPushMessageVo messageVo) {
List<String> alias = messageVo.getAlias();
// 将用户id中的-替换掉,避免使用用户id作为推送别名时出现alias 字符串不合法对应问题
alias.replaceAll(a -> a.replaceAll("-", ""));
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.alias(alias))//10000
// // TODO 与iOS联测时暂用
// .setAudience(Audience.alias(alias))//10000
.setNotification(Notification.newBuilder()
.setAlert(messageVo.getContent())
.addPlatformNotification(AndroidNotification.newBuilder()
.setTitle(messageVo.getTitle())
// .setIntent(intent)
// 跳转路径参照文档:https://docs.jiguang.cn/jpush/practice/intent 安卓端无需使用addExtras(extras)
.addExtras(messageVo.getExtras())
.build())
.addPlatformNotification(IosNotification.newBuilder()
.setAlert(messageVo.getTitle())
.incrBadge(1)
// ↓该方法客户端接受后为固定值,无法达到实际需求
// .addExtra("extra_key", "extra_value").build())
// ↓此处为iOS通知点击跳转后提供给客户端的参数,单个参数可以使用.addExtra("extras", iosUr)-->参照文档https://docs.jiguang.cn/jpush/practice/intent_ios
.addExtras(messageVo.getExtras()).build())
.build())
.setOptions(Options.newBuilder()
// 此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
.setApnsProduction(false)
// 此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天;
.setTimeToLive(43200)
.build())
.build();
}
/**
* 直接推送消息
*
* @param messageVo
* @return long:msg_id
*/
public long pushMessage(JPushMessageVo messageVo) {
final PushPayload payload = buildPushObject_android_and_ios(messageVo);
try {
// 删除定时任务
if (StringUtils.isNotNull(messageVo.getScheduleId())) {
jpushClient.deleteSchedule(messageVo.getScheduleId());
}
// 创建定时任务发送
PushResult result = jpushClient.sendPush(payload);
return result.msg_id;
} catch (APIConnectionException e) {
throw new RuntimeException(e);
} catch (APIRequestException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 创建定时任务推送消息
* 返回-1:表示队列已满,无法创建新的定时任务
*
* @param messageVo
* @return string:scheduleId
*/
public String sendBySchedule(JPushMessageVo messageVo) {
final PushPayload payload = buildPushObject_android_and_ios(messageVo);
try {
// 任务已存在则修改
if (StringUtils.isNotNull(messageVo.getScheduleId())) {
// 修改任务
jpushClient.updateSchedulePush(messageVo.getScheduleId(), payload);
return messageVo.getScheduleId();
} else {
ScheduleListResult scheduleList = jpushClient.getScheduleList();
if (scheduleList.getTotal_count() >= 100) {// 无法创建更多任务,推送消息任务队列已满
return "-1";
}
// 创建新任务
ScheduleResult singleSchedule = jpushClient.createSingleSchedule(messageVo.getScheduleName(), DateUtils.formatDateTime(messageVo.getPushTime()), payload, MASTER_SECRET, APP_KEY);
return singleSchedule.getSchedule_id();
}
} catch (APIConnectionException e) {
throw new RuntimeException(e);
} catch (APIRequestException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 删除定时推送任务
*
* @param scheduleId
*/
public void deleteSchedule(String scheduleId) {
try {
jpushClient.deleteSchedule(scheduleId);
} catch (APIConnectionException e) {
throw new RuntimeException(e);
} catch (APIRequestException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 查询定时任务消息列队剩余数
*/
public Integer taskMessageNum() {
try {
ScheduleListResult scheduleList = jpushClient.getScheduleList();
int count = scheduleList.getTotal_count();
if (count >= 100) {// 无法创建更多任务,推送消息任务队列已满
return 0;
} else {
return 100 - count;
}
} catch (APIConnectionException e) {
throw new RuntimeException(e);
} catch (APIRequestException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
三、消息实体类
package com.jddz.cloud.xxx.util;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class JPushMessageVo implements Serializable {
/**
* 任务ID
*/
private String scheduleId;
/**
* 任务名字
*/
private String scheduleName;
/**
* 定时任务发发送时间,eg 2023-12-12 10:00:00
*/
private Date pushTime;
/**
* 标题
*/
private String title;
/**
* 发送内容
*/
private String content;
/**
* 发送对象-别名
*/
private List<String> alias;
/**
* MESSAGE_TYPE:消息类型(根据业务定)
*/
private Integer messageType;
/**
* EXTRAS:跳转详情时所需参数
*/
private Map<String, String> extras;
}
备注:在serviceImply层调用时,使用:JPushUtil.getInstance().整理工具包中的方法