个推推送

  1. 引入maven依赖
    
        com.gexin.platform
        gexin-rp-sdk-http
        4.0.1.17
    
     
        
            getui-nexus
            http://mvn.gt.igexin.com/nexus/content/repositories/releases/
        
     
    2.个推消息接口
    package component.invoker.manager.push;
    
    import component.invoker.domain.wrapper.message.PushMessage;
    /**
     * @author wangbowen
     * @description 个推消息接口
     * @Date 2018/5/14
     * @since 1.0.0
     */
    public interface PushMessageExecutor {
        /**
         * 推送消息
         * @param message 消息对象
         * @return boolean
         */
        boolean send(PushMessage message);
    }
    
    3.个推消息实现接口
    package component.invoker.manager.push.support;
    
    import com.gexin.rp.sdk.base.IPushResult;
    import component.invoker.domain.wrapper.message.PushMessage;
    import component.invoker.manager.push.PushMessageExecutor;
    import component.invoker.manager.push.template.TransmissionMessageTemplate;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.Resource;
    import java.util.Map;
    import java.util.Objects;
    
    /**
     * @author wangbowen
     * @description
     * @Date 2018/5/14
     * @since 1.0.0
     */
    @Component
    public class PushMessageExecutorSupport implements PushMessageExecutor {
        @Resource
        private MessageHelper notificationMessageHelper;
        @Override
        public boolean send(PushMessage message) {
            if(Objects.nonNull(message)){
                notificationMessageHelper = new MessageHelper();
                //设置消息的模板
                notificationMessageHelper.setMessageTemplate(new TransmissionMessageTemplate());
                //发送消息
                IPushResult iPushResult = notificationMessageHelper.sendMessage(message);
                //获取返回结果
                Map result = iPushResult.getResponse();
                String ok = result.get("result").toString();
                if(ok.equals("ok")){
                    return true;
                }
    
            }
            return false;
        }
    }
    
    4.个推消息帮助类
    package component.invoker.manager.push.support;
    
    import com.gexin.rp.sdk.base.IPushResult;
    import com.gexin.rp.sdk.base.impl.ListMessage;
    import com.gexin.rp.sdk.base.impl.Target;
    import com.gexin.rp.sdk.http.IGtPush;
    import com.gexin.rp.sdk.template.AbstractTemplate;
    import component.invoker.domain.wrapper.message.PushMessage;
    import component.invoker.manager.push.PushMessageExecutor;
    import component.invoker.manager.push.config.MessageProperties;
    import component.invoker.manager.push.constant.MessageConstant;
    import component.invoker.manager.push.template.DefaultNotificationMessageTemplate;
    import component.invoker.manager.push.template.MessageTemplate;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.stereotype.Component;
    import org.springframework.util.Assert;
    
    import javax.annotation.Resource;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @author wangbowen
     * @description 个推消息辅助类
     * @Date 2018/5/14
     * @since 1.0.0
     */
    @Component
    @EnableConfigurationProperties(MessageProperties.class)
    public class MessageHelper {
        private Logger logger =LoggerFactory.getLogger(MessageHelper.class);
    
        /**
         * 消息对象
         */
        private PushMessage messageEntity;
        /**
         * 消息模板
         */
        private MessageTemplate messageTemplate;
    
        @Resource
        private MessageProperties messageProperties;
    
    
    
        /**
         * 发送消息
         * @param message 消息
         * @return IPushResult
         */
        public IPushResult sendMessage(PushMessage message){
            return this.setNotificationMessageEntity(message).checkNotNull().execute();
        }
    
        /**
         * 检验
         * @return
         */
        private MessageHelper checkNotNull(){
            Assert.notNull(getNotificationMessageEntity().getText(),"标题不能为空");
            Assert.isTrue(getNotificationMessageEntity().getClientIds().size()>0, "应用App clientId信息不能为空");
            return this;
        }
    
        private IPushResult execute(){
            messageProperties = new MessageProperties();
            logger.info("---------------开始发送消息----------------");
            String appId = messageProperties.getAppId();
            String appKey = messageProperties.getAppKey();
            String masterSecret = messageProperties.getMasterSecret();
            String host = messageProperties.getHost();
    
            IGtPush push = new IGtPush(host, appKey, masterSecret);
            // 定义"点击链接打开通知模板",并设置标题、内容、链接
            if(messageTemplate==null){
                messageTemplate = new DefaultNotificationMessageTemplate();
            }else{
                messageTemplate = getMessageTemplate();
            }
            AbstractTemplate notificationTemplate = messageTemplate.createTemplate(getNotificationMessageEntity());
            notificationTemplate.setAppId(appId);
            notificationTemplate.setAppkey(appKey);
    
            // 定义"AppMessage"类型消息对象,设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
            ListMessage message = createListMessage(notificationTemplate);
            //设置发送群体
            List targets = getTargets();
            String taskId = push.getContentId(message);
            IPushResult ret = push.pushMessageToList(taskId, targets);
            logger.info("------------发送消息结果:"+ret.getResponse().toString()+".------------");
            return ret;
        }
    
        /**
         * 创建消息
         * @param notificationTemplate 消息模板
         * @return ListMessage
         */
        private ListMessage createListMessage(AbstractTemplate notificationTemplate){
            ListMessage message = new	ListMessage();
            message.setData(notificationTemplate);
            // 设置消息离线,并设置离线时间
            message.setOffline(true);
            // 离线有效时间,单位为毫秒,可选
            message.setOfflineExpireTime(MessageConstant.offlineExpireTime);
            return message;
    
        }
    
        /**
         * 消息目标对象
         * @return
         */
        private List getTargets(){
           List clientIds = getNotificationMessageEntity().getClientIds();
            List targets = new ArrayList<>();
            clientIds.forEach(clientId->{
                Target target = new Target();
                target.setClientId(clientId);
                target.setAppId(messageProperties.getAppId());
                targets.add(target);
            });
            return targets;
        }
        public PushMessage getNotificationMessageEntity() {
            return messageEntity;
        }
    
        public MessageTemplate getMessageTemplate() {
            return messageTemplate;
        }
    
        public MessageHelper setNotificationMessageEntity(PushMessage notificationMessageEntity) {
            this.messageEntity = notificationMessageEntity;
            return this;
        }
        public MessageHelper setMessageTemplate(MessageTemplate messageTemplate) {
            this.messageTemplate = messageTemplate;
            return this;
        }
    
        /**
         * 测试
         * @param args
         */
        public static void main(String[] args) {
            String clientId = "f709d9df32970b940844367727e2e76d";
           List clientIds = new ArrayList<>();
            clientIds.add(clientId);
            PushMessage message = new PushMessage();
            message.setText("你有一条最新的消息");
            message.setTitle("消息通知");
            message.setClientIds(clientIds);
            PushMessageExecutor pushMessageExecutor = new PushMessageExecutorSupport();
            pushMessageExecutor.send(message);
        }
    }
    
    5.消息模板接口
    package component.invoker.manager.push.template;
    
    import com.gexin.rp.sdk.template.AbstractTemplate;
    import component.invoker.domain.wrapper.message.PushMessage;
    /**
     * @author wangbowen
     * @description 消息模板接口
     * @Date 2018/5/14
     * @since 1.0.0
     */
    public interface MessageTemplate {
        /**
         * 创建消息模板
         * @param message 消息对象
         * @return AbstractTemplate
         */
        AbstractTemplate createTemplate(PushMessage message);
    }
    
    6.消息模板实现接口,默认通知类型的模板
    package component.invoker.manager.push.template;
    
    import com.gexin.rp.sdk.template.AbstractTemplate;
    import com.gexin.rp.sdk.template.NotificationTemplate;
    import com.gexin.rp.sdk.template.style.Style0;
    import component.invoker.domain.wrapper.message.PushMessage;
    import component.invoker.manager.push.constant.MessageConstant;
    /**
     * @author wangbowen
     * @description 默认的点击通知打开应用的消息模板
     * @Date 2018/5/14
     * @since 1.0.0
     */
    public class DefaultNotificationMessageTemplate implements MessageTemplate {
        public AbstractTemplate createTemplate(PushMessage message) {
            NotificationTemplate template = new NotificationTemplate();
            // 透传消息设置,1为强制启动应用,客户端接收到消息后就会立即启动应用;2为等待应用启动
            template.setTransmissionType(MessageConstant.TYPE_LAUNCH_APP);
            template.setTransmissionContent(message.getTransmissionContent());
            Style0 style = new Style0();
            // 设置通知栏标题与内容
            style.setTitle(message.getTitle());
            style.setText(message.getText());
            // 配置通知栏图标
            style.setLogo(MessageConstant.logo);
            // 配置通知栏网络图标
            style.setLogoUrl(MessageConstant.logoUrl);
            // 设置通知是否响铃,震动,或者可清除
            style.setRing(true);
            style.setVibrate(true);
            style.setClearable(true);
            template.setStyle(style);
            return template;
        }
    }
    

    package component.invoker.manager.push.template;
    
    import com.gexin.rp.sdk.base.payload.APNPayload;
    import com.gexin.rp.sdk.template.AbstractTemplate;
    import com.gexin.rp.sdk.template.TransmissionTemplate;
    import component.invoker.domain.wrapper.message.PushMessage;
    import component.invoker.manager.push.constant.MessageConstant;
    /**
     * @author wangbowen
     * @description 透传消息模板
     * @Date 2018/5/14
     * @since 1.0.0
     */
    public class TransmissionMessageTemplate implements MessageTemplate {
        public AbstractTemplate createTemplate(PushMessage message) {
            TransmissionTemplate template = new TransmissionTemplate();
            // 透传消息设置,1为强制启动应用,客户端接收到消息后就会立即启动应用;2为等待应用启动
            template.setTransmissionType(MessageConstant.TYPE_WAIT_FOR_CLICK);
            //设置透传消息内容,必须满足以下的格式
            String content = "{title:'"+message.getTitle()+"',content:'"+message.getText()+"',payload:'"+message.getTransmissionContent()+"'}";
            template.setTransmissionContent(content);
            //设置IOS
            APNPayload payload = new  APNPayload();
            payload.setBadge(MessageConstant.TYPE_LAUNCH_APP);
            payload.setContentAvailable(MessageConstant.TYPE_LAUNCH_APP);
            payload.setSound("default");
            payload.setCategory("$由客户端定义");
            payload.setAlertMsg(new APNPayload.SimpleAlertMsg(""));
            //字典模式使用
            // payload.setAlertMsg(getDictionaryAlertMsg());
            template.setAPNInfo(payload);
            return template;
        }
        private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(){
            APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
            alertMsg.setBody("body");
            alertMsg.setActionLocKey("ActionLockey");
            alertMsg.setLocKey("LocKey");
            alertMsg.addLocArg("loc-args");
            alertMsg.setLaunchImage("launch-image");
            // IOS8.2以上版本支持
            alertMsg.setTitle("Title");
            alertMsg.setTitleLocKey("TitleLocKey");
            alertMsg.addTitleLocArg("TitleLocArg");
            return alertMsg;
        }
    
    }
    

    package component.invoker.manager.push.template;
    
    import com.gexin.rp.sdk.template.AbstractTemplate;
    import com.gexin.rp.sdk.template.LinkTemplate;
    import component.invoker.domain.wrapper.message.PushMessage;
    import component.invoker.manager.push.constant.MessageConstant;
    /**
     * @author wangbowen
     * @description 点击通知打开网页模板
     * @Date 2018/5/14
     * @since 1.0.0
     */
    public class LinkMessageTemplate implements MessageTemplate {
        public AbstractTemplate createTemplate(PushMessage message) {
            LinkTemplate template = new LinkTemplate();
            // 设置通知栏标题与内容
            template.setText(message.getTitle());
            template.setText(message.getText());
            // 配置通知栏图标
            template.setLogo(MessageConstant.logo);
            // 配置通知栏网络图标
            template.setLogoUrl(MessageConstant.logoUrl);
            // 设置通知是否响铃,震动,或者可清除
            template.setIsRing(true);
            template.setIsVibrate(true);
            template.setIsClearable(true);
            // 设置打开的网址地址
            template.setUrl(message.getUrl());
            return template;
        }
    }
    
    6.个推配置项
    package component.invoker.manager.push.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    /**
     * @author wangbowen
     * @description 个推配置
     * @Date 2018/5/14
     * @since 1.0.0
     */
    @ConfigurationProperties("invoker.gexin")
    public class MessageProperties {
        /**
         *由IGetui管理页面生成,是您的应用与SDK通信的标识之一,每个应用都对应一个唯一的AppID
         */
        private String appId="GQAR1d7BMA6fkk18p76BeA";
    
        /**
         *预先分配的第三方应用对应的Key,是您的应用与SDK通信的标识之一
         */
        private String appKey="Y2anGfezbu5xYe1EPakcY4";
        /**
         * 个推服务端API鉴权码,用于验证调用方合法性。在调用个推服务端API时需要提供
         */
        private String masterSecret="iko2xXLGnf9j6EGCCZWqb8";
    
        /**
         * 应用地址 :http://sdk.open.api.igexin.com/apiex.htm
         */
        private String  host ="http://sdk.open.api.igexin.com/apiex.htm";
    
        public String getAppId() {
            return appId;
        }
    
        public void setAppId(String appId) {
            this.appId = appId;
        }
    
        public String getAppKey() {
            return appKey;
        }
    
        public void setAppKey(String appKey) {
            this.appKey = appKey;
        }
    
        public String getMasterSecret() {
            return masterSecret;
        }
    
        public void setMasterSecret(String masterSecret) {
            this.masterSecret = masterSecret;
        }
    
        public String getHost() {
            return host;
        }
    
        public void setHost(String host) {
            this.host = host;
        }
    }
    
    7.接口常量类
    package component.invoker.manager.push.constant;
    
    /**
     * @author wangbowen
     * @description 个推消息常量
     * @Date 2018/5/14
     * @since 1.0.0
     */
    public interface MessageConstant {
         String logo="";
         String logoUrl="icon.png";
         Integer offlineExpireTime =Integer.MAX_VALUE * 1000 * 3600;
         //透传消息设置,1为强制启动应用,客户端接收到消息后就会立即启动应用;2为等待应用启动
          int TYPE_LAUNCH_APP = 1;
          int TYPE_WAIT_FOR_CLICK = 2;
    }
    
    8.消息传输对象
    package component.invoker.manager.push.domain;
    
    import java.util.List;
    
    /**
     * @author wangbowen
     * @description 个推消息实体类
     * @Date 2018/5/14
     * @since 1.0.0
     */
    public class MessageEntity {
        /**
         * 消息标题
         */
        private String  title;
    
        /**
         * 消息内容
         */
        private String  text;
        /**
         * 透传消息
         */
        private String transmissionContent;
    
        /**
         * 消息链接
         */
        private  String  url;
        /**
         * 消息目标对象
         */
        private List clientIds;
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
        public String getTransmissionContent() {
            return transmissionContent;
        }
    
        public void setTransmissionContent(String transmissionContent) {
            this.transmissionContent = transmissionContent;
        }
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public List getClientIds() {
            return clientIds;
        }
    
        public void setClientIds(List clientIds) {
            this.clientIds = clientIds;
        }
    }
    

你可能感兴趣的:(java)