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

  1. pom文件添加jar包
       
           cn.jpush.api
           jpush-client
           3.3.3
       

       
            cn.jpush.api
            jpush-client
       

        
            cn.jpush.api
            jiguang-common
            1.0.9
            
                
                    com.google.code.gson
                    gson
                
            
        

        
            com.google.code.gson
            gson
            2.8.2
        
  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 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 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 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 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 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 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) {
      //回调操作
    }
});

你可能感兴趣的:(服务端使用jpush实现APP消息通知)