基于SpringBoot给IOS发送消息提醒通知

基于SpringBoot给苹果消息通知服务器APNS发送消息通知

一.导入依赖/jar包

 <!-- TODO 苹果手机推送:Java推送至APNS服务器start -->
        <dependency>
            <groupId>com.eatthepath</groupId>
            <artifactId>pushy</artifactId>
            <version>0.15.0</version>
        </dependency>
        <dependency>
            <groupId>com.notnoop.apns</groupId>
            <artifactId>apns</artifactId>
            <version>1.0.0.Beta6</version>
        </dependency>
        <!-- TODO 苹果手机推送:Java推送至APNS服务器end -->

二.发送消息通知工具类

@Slf4j
@Component
public class APNsUtil {

    private static ApnsClient apnsClient = null;
    private static final String p12Password = "xinao111222";

    /**
     * APNs推送
     *
     * @param deviceToken IOS等终端设备注册后返回的DeviceToken
     * @param topic       这是你的主题,大多数情况是bundleId
     * @param alert       json格式内容-发送的消息体
     * @param badge       app提醒消息圆点数
     * @param time        有效时间
     * @param priority    发送策略 apns-priority 10为立即 5为省电
     * @param pushType    推送方式,主要有alert,background,voip,complication,fileprovider,mdm
     * @return response
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static PushNotificationResponse<SimpleApnsPushNotification> ApplePush(String deviceToken, String topic, String alert, int badge, Long time, DeliveryPriority priority, PushType pushType) throws ExecutionException, InterruptedException {
        // 有效时间
        Date invalidationTime = new Date(System.currentTimeMillis() + time);
        Instant instant = invalidationTime.toInstant();
        // 构造一个APNs的推送消息实体

        String payload="{\"aps\":{\"alert\":\"" + alert + "\",\"badge\":" + badge + ",\"sound\": \"default\"}}";
        SimpleApnsPushNotification msg = new SimpleApnsPushNotification(deviceToken, topic, payload, instant, priority, pushType);
        // 开始推送
        PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> future = getAPNSConnect().sendNotification(msg);
        PushNotificationResponse<SimpleApnsPushNotification> response = future.get();
        return response;
    }

    public static ApnsClient getAPNSConnect() {

        if (apnsClient == null) {
            try {
                // 四个线程
                EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
                
                String resourceLocation = null;
                // 解释如下 xinaoAPNS.p12文件, 该文件是IOS在苹果官网注册时所得,这里用的是.p12结尾文件,还用.p8结尾文件
                // 该两个if语句是根据环境去找配置文件
				// add by Mr.song start 20220707 
                if ("prod".equals(SysProperties.getEnvironment())) {
                    resourceLocation = "/home/appadmin/enn/xinaoAPNS.p12";
                }
                if ("test".equals(SysProperties.getEnvironment())) {
                    resourceLocation = "/data/lipei/web/app/zzfw/enn/xinaoAPNS.p12";
                    File file  = new File("src/main/resources/template/xinaoAPNS.p12");
                    if (file.exists()) {
                        resourceLocation =ResourceUtils.CLASSPATH_URL_PREFIX +"template/xinaoAPNS.p12";
                    }
                }
                // add by Mr.song end 20220707
                File file = ResourceUtils.getFile(resourceLocation);
                apnsClient = new ApnsClientBuilder()
                        //APNS生产IP地址
                        .setApnsServer(ApnsClientBuilder.PRODUCTION_APNS_HOST)
                        //P12配置文件时注册密码
                        .setClientCredentials(file, p12Password)
                        //用于设置服务器与苹果服务器建立几个链接通道,这里是建立了四个,链接通道并不是越多越好的,具体百度
                        .setConcurrentConnections(4)
                        //的作用是建立几个线程来处理,说白了就是多线程,我这里设置的都是4,相当于16个线程同时处理。
                        .setEventLoopGroup(eventLoopGroup).build();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("Get IOS Connect Exception, Please Check:{}", e.getMessage());
            }
        }
        return apnsClient;

    }


    public static void sendIosMsg(String deviceToken, String msgBody, int badge) {

        PushNotificationResponse<SimpleApnsPushNotification> response = null;
        try {
            response = APNsUtil.ApplePush(deviceToken, "cn.enn.epei", msgBody,badge,60 * 1000L, DeliveryPriority.IMMEDIATE, PushType.ALERT);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Ios Send Msg Fail{}",e.getMessage());
            return;
        }

        log.info("执行结果:{}",response.getRejectionReason());
        // 如果返回的消息中success为true那么成功,否则失败!
        System.err.println("如果返回的消息中success为true那么成功,否则失败!"+response);
        log.info("如果返回的消息中success为true那么成功,否则失败!{}",JSON.toJSONString(response));
    }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山雨木公

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值