服务端使用jpush实现APP消息通知

  1. pom文件添加jar包
       <dependency>
           <groupId>cn.jpush.api</groupId>
           <artifactId>jpush-client</artifactId>
           <version>3.3.3</version>
       </dependency>

       <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jpush-client</artifactId>
       </dependency>

        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jiguang-common</artifactId>
            <version>1.0.9</version>
            <exclusions>
                <exclusion>
                    <groupId>com.google.code.gson</groupId>
                    <artifactId>gson</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>
  1. JpushUtils工具类
package com.tgy.znh.svc.util;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
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.push.model.notification.WinphoneNotification;
import io.netty.handler.codec.http.HttpMethod;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

public class JpushUtils {
    private static final Logger log = LoggerFactory.getLogger(JpushUtils.class);
    private String masterSecret;
    private String appKey;

    public JpushUtils setMasterSecret(String masterSecret) {
        this.masterSecret = masterSecret;
        return this;
    }

    public JpushUtils setAppKey(String appKey) {
        this.appKey = appKey;
        return this;
    }

    /**
     * 生成极光推送对象PushPayload(采用java SDK)
     *
     * @param alias
     * @param alert
     * @return PushPayload
     */
    public PushPayload buildPushObject_android_ios_alias_alert(String alias, String alert) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境(测试使用参数)
                        .setTimeToLive(90)//消息在JPush服务器的失效时间(测试使用参数)
                        .build())
                .build();
    }

    /**
     * 根据别名推送到所有设备
     *
     * @param title        标题
     * @param notification 内容
     * @param extras       额外附加内容
     * @return
     */
    public PushPayload buildPushObject_all_alias_alert(String title, String notification, String alias,
                                                       Map<String, String> extras, boolean forProduction) {
        PushPayload.Builder builder = PushPayload.newBuilder()
                //推送平台
                .setPlatform(Platform.all());
        //推送别名
        if (StringUtils.isEmpty(alias)) {
            //广播所有用户
            builder.setAudience(Audience.all());
        } else {
            //根据别名推送
            builder.setAudience(Audience.alias(alias));
        }
        //通知信息
        builder.setNotification(
                Notification
                        .newBuilder()
                        .addPlatformNotification(
                                IosNotification.newBuilder()
                                        .setAlert(notification)
                                        //autoBadge()方法为自动获取通知角标数量
                                        .setSound("happy.caf").autoBadge()
                                        .addExtras(extras).build())
                        .addPlatformNotification(
                                AndroidNotification.newBuilder()
                                        .setAlert(notification)
                                        .setTitle(title).addExtras(extras)
                                        .build())
                        .addPlatformNotification(
                                WinphoneNotification.newBuilder()
                                        .setAlert(notification)
                                        .addExtras(extras).build())
                        .build())
                /**
                 * 如果目标平台为 iOS 平台 需要在 options 中通过 apns_production 字段来设定推送环境。
                 * True 表示推送生产环境,False 表示要推送开发环境; 如果不指定则为推送生产环境
                 * ios平台生产环境必须设置 apns_production 为 true 否则会导致推送失败
                 */
                .setOptions(Options.newBuilder()
                        .setApnsProduction(forProduction)
                        .build());
        return builder.build();
    }

    /**
     * 推送到所有用户
     *
     * @param title        标题
     * @param notification 内容
     * @param extras       额外附加内容
     * @return
     */
    public PushPayload buildPushObject_all(String title, String notification, String alias,
                                           Map<String, String> extras, boolean forProduction) {
        PushPayload.Builder builder = PushPayload.newBuilder()
                .setPlatform(Platform.all());
        if (StringUtils.isEmpty(alias)) {
            builder.setAudience(Audience.all());
        } else {
            builder.setAudience(Audience.all());
        }
        return builder.setNotification(
                Notification
                        .newBuilder()
                        .addPlatformNotification(
                                IosNotification.newBuilder()
                                        .setAlert(notification)
                                        .setSound("happy.caf").autoBadge()
                                        .addExtras(extras).build())
                        .addPlatformNotification(
                                AndroidNotification.newBuilder()
                                        .setAlert(notification)
                                        .setTitle(title).addExtras(extras)
                                        .build())
                        .addPlatformNotification(
                                WinphoneNotification.newBuilder()
                                        .setAlert(notification)
                                        .addExtras(extras).build())
                        .build())
                /**
                 * 如果目标平台为 iOS 平台 需要在 options 中通过 apns_production 字段来设定推送环境。
                 * True 表示推送生产环境,False 表示要推送开发环境; 如果不指定则为推送生产环境
                 */
                .setOptions(Options.newBuilder()
                        .setApnsProduction(forProduction)
                        .build())
                .build();
    }

    /**
     * 极光推送方法(采用java SDK)
     *
     * @param title
     * @param notification
     * @param extras
     * @return
     */
    //普通推送
    public PushResult push(String title, String notification, String alias, Map<String, String> extras, boolean forProduction) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        PushPayload payload = buildPushObject_all(title, notification, alias, extras, forProduction);
        try {
            return jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
            return null;
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
            return null;
        }
    }

    //异步推送
    public void pushAsync(final String title, final String notification, final String alias, final Map<String, String> extras, final boolean forProduction, final IJpushCallback callback) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(appKey, masterSecret),
                null, clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
            PushPayload payload = buildPushObject_all_alias_alert(title, notification, alias, extras, forProduction);
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    callback.onSucceed(responseWrapper);
                }
            });
        } catch (URISyntaxException e) {
            log.error("地址错误", e);
        }
    }

    public interface IJpushCallback {
        void onSucceed(ResponseWrapper responseWrapper);
    }
}
  1. 项目中推送分两个app索性抽成了两个推送方法在一个PushService中
  • service接口
public interface PushService {
    void pushToCustApp(PushBean pushBean, JpushUtils.IJpushCallback callback);
    void pushToServApp(PushBean pushBean, JpushUtils.IJpushCallback callback);
}
  • service实现类
@Service("pushService")
public class PushServiceImpl implements PushService {
    @Autowired
    private SysConfigService sysConfigService;

    private JpushUtils custAppJpush; // 客户端App
    private JpushUtils servAppJpush; // 服务端App

    private void init(){
        if (custAppJpush == null) {
            String masterSecret = sysConfigService.getValue("qfs.custapp.jpush.masterSecret");
            String appKey = sysConfigService.getValue("qfs.custapp.jpush.appKey");
            custAppJpush = new JpushUtils().setMasterSecret(masterSecret).setAppKey(appKey);
        }
        if (servAppJpush == null) {
            String masterSecret = sysConfigService.getValue("qfs.servapp.jpush.masterSecret");
            String appKey = sysConfigService.getValue("qfs.servapp.jpush.appKey");
            servAppJpush = new JpushUtils().setMasterSecret(masterSecret).setAppKey(appKey);
        }
    }

    @Override
    public void pushToCustApp(PushBean pushBean, JpushUtils.IJpushCallback callback) {
        init();
        String title = pushBean.getTitle();
        String notification = pushBean.getNotification();
        Map<String, String> extras = pushBean.getExtras();
        custAppJpush.pushAsync(title, notification, pushBean.getAlias(), extras, pushBean.isForProduction(), callback);
    }

    @Override
    public void pushToServApp(PushBean pushBean, JpushUtils.IJpushCallback callback) {
        init();
        String title = pushBean.getTitle();
        String notification = pushBean.getNotification();
        Map<String, String> extras = pushBean.getExtras();
        servAppJpush.pushAsync(title, notification, pushBean.getAlias(), extras, pushBean.isForProduction(), callback);
    }
}

  1. 最后推送操作
pushService.pushToServApp(pushBean, new JpushUtils.IJpushCallback() {
    @Override
    public void  onSucceed(ResponseWrapper responseWrapper) {
      //回调操作
    }
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,314评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,040评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,054评论 25 709
  • 有些许时间没有静静的就这样静静的静下心来,放空自己也许是被现实束缚也许是被自己埋葬静静的不想,不听,不停点上一支烟...
    余越阅读 2,394评论 0 2
  • “”我不知道如何去写一个恰当的开头,来讲述那两个老人,亦是我的父亲! 说起来,我与他们二人相处的时间并不长,我了解...
    骆生生阅读 1,072评论 1 0