IOS
使用APNS 实现IOS消息推送
前置准备:需要APNS证书
//创建APNS链接
public static ApnsClient getAPNSConnect() {
if (apnsClient == null) {
try {
// 四个线程
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
//todo prod
String resource = new ClassPathResource(ServerConstans.apnsfilepath).getPath();
// String resource = new File("/xxxxxxxxx/xxxxxxxx/src/main/resources/apns/xxxxx_uat_apns.p12").getPath();
String resourceLocation = new File(resource).getAbsolutePath();
File file = ResourceUtils.getFile(resourceLocation);
apnsClient = new ApnsClientBuilder()
//todo prod/uat
// .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
.setApnsServer(ApnsClientBuilder.PRODUCTION_APNS_HOST) //apns服务器地址
.setClientCredentials(file, ServerConstans.apnspass) //证书密码
.setConcurrentConnections(4) //线程连接数
.setEventLoopGroup(eventLoopGroup).build(); //线程组
} catch (Exception e) {
e.printStackTrace();
log.error("Get IOS Connect Exception, Please Check:{}", e.getMessage());
}
}
return apnsClient;
}
/**
* 1.deviceToken : IOS等终端设备注册后返回的DeviceToken
* 2.topic :这是你的主题,大多数情况是bundleId
* 3.payload : 发送数据的请求体
* 4.time : 有效时间
* 5.priority : 发送策略 apns-priority 10为立即 5为省电
* 6.pushType 推送方式,主要有alert,background,voip,complication,fileprovider,mdm
*/
public static PushNotificationResponse<SimpleApnsPushNotification> ApplePush(String deviceToken, String topic,
String payload,
Long time, DeliveryPriority priority,
PushType pushType) throws ExecutionException, InterruptedException {
// 有效时间
Date invalidationTime = new Date(System.currentTimeMillis() + time);
Instant instant = invalidationTime.toInstant();
SimpleApnsPushNotification msg = new SimpleApnsPushNotification(deviceToken, topic, payload, instant, priority, pushType);
// 开始推送
PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> future = getAPNSConnect().sendNotification(msg);
PushNotificationResponse<SimpleApnsPushNotification> response = future.get();
log.info("PushNotificationResponse response:{} ",response);
return response;
}
#另外推送可以增加重试机制,防止推送失败
Retryer<PushNotificationResponse<SimpleApnsPushNotification>> retryer = RetryerBuilder.<PushNotificationResponse<SimpleApnsPushNotification>>newBuilder()
.retryIfException() //如果出现异常
.withStopStrategy(StopStrategies.stopAfterAttempt(3)) //重试次数
.withWaitStrategy(WaitStrategies.fixedWait(10, TimeUnit.SECONDS)) //间隔时长
.build();
PushNotificationResponse<SimpleApnsPushNotification> response = null;
try {
//retry 逻辑
Callable<PushNotificationResponse<SimpleApnsPushNotification>> task = () ->
APNsUtil.ApplePush(deviceToken, "你的topic", "你的请求体,是个json,后面会附上json结构图,可以参考", 60 * 1000L,
DeliveryPriority.IMMEDIATE, PushType.ALERT);
try {
response = retryer.call(task);
} catch (RetryException | ExecutionException e) {
System.out.println(" Retry failed after maximum attempts: " + e.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
log.error(" Ios Send Msg Fail{}", e.getMessage());
return;
}
JSON格式
Android
public boolean androidPushMsgxxxxxxxxx(PushMsgVO androidMsg) {
Notification notice = Notification.builder().setBody(androidMsg.getBody()).setTitle(androidMsg.getTitle()).build();
builder.setToken(androidMsg.getDeviceToken());// 客户端申请到的token
builder.setNotification(notice);
builder.putData("action","xxxxxxx"); //自定义属性
Message message = builder.build();
try {
log.info(" message :"+ JSONObject.toJSONString(message));
String fcm = FirebaseMessaging.getInstance().send(message);
log.info(" push android message success. " + fcm);
} catch (Exception e) {
log.error("error message :{}", e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
附MessageVo
{
"header": "",
"body": "自己可以写哦 Thank you for using my app!",
"title": "自己写的头",
"deviceToken": "设备id"
}