个推消息推送SDK快速Springboot项目集成案例

这些步骤仅提供了一个基本的集成个推的框架,具体的实现和细节可能因个推的版本和需求而有所不同。因此,建议根据个推的官方文档进行详细的配置和使用说明,并参考相关示例代码来完成集成。

官网:个推消息推送—Android和iOS推送SDK快速集成,免费使用

文档:开发前必读-个推文档中心

案例:https://github.com/GetuiLaboratory/getui-pushapi-java-client-v2

  1. 用户登陆手机 将clientid和用户id绑定
    @Autowired
    private ClientInfoService clientInfoService;
    
    @ApiOperation(value = "用户绑定")
    @PostMapping("/bind")
    public ApiResult submit(@RequestBody ClientInfoBindDTO bindDTO) {
        this.clientInfoService.bind(bindDTO);
        return R.success("操作成功");
    }
    
    
    @Service
    public class ClientInfoServiceImpl extends ServiceImpl<ClientInfoMapper, ClientInfo> implements ClientInfoService{
    
        @Override
        public void bind(ClientInfoBindDTO bindDTO) {
            ClientInfo one = this.getOne(new LambdaQueryWrapper<ClientInfo>().eq(ClientInfo::getUserId, bindDTO.getUserId()).eq(ClientInfo::getPlatform, bindDTO.getPlatform()));
            ClientInfo clientInfo = ModelMapper.map(bindDTO, ClientInfo.class);
            if (one == null) {
                this.save(clientInfo);
            } else {
                if (!one.getCid().equals(bindDTO.getCid())) {
                    // 更新CID
                    clientInfo.setId(one.getId());
                    this.updateById(clientInfo);
                }
            }
        }
    }
    
    
    /**
     * app消息推送表
     * @TableName spang_client_info
     */
    @TableName(value ="spang_client_info")
    @Data
    public class ClientInfo implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        /**
         * 主键
         */
        @JsonSerialize(using = ToStringSerializer.class)
        @ApiModelProperty(value = "主键id")
        @TableId(value = "id", type = IdType.ASSIGN_ID)
        private Long id;
    
        /**
         * 用户主键ID
         */
        @TableField(value = "user_id")
        private Long userId;
    
        /**
         * 推送使用的clientId
         */
        @TableField(value = "cid")
        private String cid;
    
        /**
         * 所属平台
         */
        @TableField(value = "platform")
        private String platform;
    
        /**
         * 别名
         */
        @TableField(value = "alias")
        private String alias;
    
        /**
         * 城市
         */
        @TableField(value = "city")
        private String city;
    
    }
    
    @Data
    @ApiModel(description = "绑定系统用户与个推用户的clientId")
    public class ClientInfoBindDTO implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @ApiModelProperty(value = "用户主键ID")
        private Long userId;
    
        @ApiModelProperty(value = "个推对应的用户客户端ID")
        private String cid;
    
        @ApiModelProperty(value = "个推对应的用户客户端平台类型")
        private String platform;
    }
    
    
    DROP TABLE IF EXISTS `spang_client_info`;
    CREATE TABLE `spang_client_info`  (
      `id` bigint(20) NOT NULL COMMENT '主键',
      `user_id` bigint(20) NOT NULL COMMENT '用户主键ID',
      `cid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '推送使用的clientId',
      `platform` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '所属平台',
      `alias` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '别名',
      `city` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '城市',
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = 'app消息推送表' ROW_FORMAT = Dynamic;

  2. 导入个推的 Java SDK 包:在 Maven 或 Gradle 中添加个推的 Java SDK 依赖项。例如,在 Maven 中的 pom.xml 文件中添加以下依赖项:
    <!--个推-->
     <dependency>
       <groupId>com.getui.push</groupId>
       <artifactId>restful-sdk</artifactId>
       <version>1.0.0.1</version>
    </dependency>

  3. 配置个推的参数:根据个推的配置,创建一个配置文件(例如 getui.properties)来存储个推的相关参数,如 AppID、AppKey、MasterSecret 等。在 Spring Boot 的配置文件(如 application.ymlapplication.properties)中,设置个推参数的值。

    /**
    app:
      appId: xxxxx
      appKey: xxxxx
      masterSecret: xxxxxx
      packageName: xxxxxxx
    **/
    
    @Data
    @Configuration
    @ConfigurationProperties(prefix = "app")
    public class PushConfig {
        public String appId;
        public String appKey;
        public String masterSecret;
        public String packageName;
    
        private PushProvider pushProvider;
    
        /**
         * 个推获取初始化信息
         *
         * @param
         * @return com.spang.emergency.service.PushProvider
         */
        public PushProvider getPushProvider() {
            if (this.pushProvider == null) {
                pushProvider = new PushProvider(appId, appKey, masterSecret, packageName);
            } else {
                pushProvider.refreshApi();
            }
            return pushProvider;
        }
    
        public PushProvider readySendMsg() {
            return pushProvider;
        }
    }
  4. 创建个推的服务类:创建一个 Java 类,用于封装个推相关的操作。在该类中,注入配置文件中的参数,并实现推送消息、绑定用户等个推功能的方法。

    import cn.hutool.core.util.StrUtil;
    import cn.hutool.json.JSONObject;
    import cn.hutool.json.JSONUtil;
    import com.getui.push.v2.sdk.ApiHelper;
    import com.getui.push.v2.sdk.GtApiConfiguration;
    import com.getui.push.v2.sdk.api.PushApi;
    import com.getui.push.v2.sdk.api.UserApi;
    import com.getui.push.v2.sdk.common.ApiResult;
    import com.getui.push.v2.sdk.dto.req.*;
    import com.getui.push.v2.sdk.dto.req.message.PushBatchDTO;
    import com.getui.push.v2.sdk.dto.req.message.PushChannel;
    import com.getui.push.v2.sdk.dto.req.message.PushDTO;
    import com.getui.push.v2.sdk.dto.req.message.PushMessage;
    import com.getui.push.v2.sdk.dto.req.message.android.AndroidDTO;
    import com.getui.push.v2.sdk.dto.req.message.android.ThirdNotification;
    import com.getui.push.v2.sdk.dto.req.message.android.Ups;
    import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
    import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
    import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.util.CollectionUtils;
    
    import java.util.*;
    
    @Slf4j
    public class PushProvider {
        private String appId;
        private String appKey;
        private String masterSecret;
        private String packageName;
        private ApiHelper apiHelper;
        private static PushApi pushApi;
        private static UserApi userApi;
    
        public PushProvider(String appId, String appKey, String masterSecret, String packageName) {
            this.appId = appId;
            this.appKey = appKey;
            this.masterSecret = masterSecret;
            this.packageName = packageName;
            GtApiConfiguration apiConfiguration = new GtApiConfiguration();
            //填写应用配置
            apiConfiguration.setAppId(appId);
            apiConfiguration.setAppKey(appKey);
            apiConfiguration.setMasterSecret(masterSecret);
            // 实例化ApiHelper对象,用于创建接口对象
            apiHelper = ApiHelper.build(apiConfiguration);
            pushApi = apiHelper.creatApi(PushApi.class);
            userApi = apiHelper.creatApi(UserApi.class);
        }
    
        /**
         * 配置数据有变化,则刷新个推api认证信息
         */
        public void refreshApi() {
            GtApiConfiguration apiConfiguration = new GtApiConfiguration();
            //填写应用配置
            apiConfiguration.setAppId(appId);
            apiConfiguration.setAppKey(appKey);
            apiConfiguration.setMasterSecret(masterSecret);
            // 实例化ApiHelper对象,用于创建接口对象
            apiHelper = ApiHelper.build(apiConfiguration);
            pushApi = apiHelper.creatApi(PushApi.class);
            userApi = apiHelper.creatApi(UserApi.class);
        }
    
        /**
         * 个推批量推送
         */
        public void pushBatchByCid(List<String> clientIds, Message message) {
            try {
                if (CollectionUtils.isEmpty(clientIds)) {
                    return;
                }
                PushBatchDTO pushBatchDTO = new PushBatchDTO();
                List<PushDTO<Audience>> msgList = new ArrayList<>(clientIds.size());
                for (String clientId : clientIds) {
                    PushDTO<Audience> pushDTO = buildPushDTO(message);
                    pushDTO.setAudience(buildAudienceByCid(clientId));
                    msgList.add(pushDTO);
                }
                pushBatchDTO.setAsync(true);
                pushBatchDTO.setMsgList(msgList);
                ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushBatchByCid(pushBatchDTO);
                judgeResult(apiResult);
            } catch (Exception e) {
                // 个推是否成功不关心,此处异常不处理
            }
        }
    
        /**
         * 个推单人推送
         * @param clientId
         * @param message
         * @return java.lang.Boolean
         */
        public void pushToSingleByCid(String clientId, Message message) {
            try {
                PushDTO<Audience> pushDTO = buildPushDTO(message);
                Audience audience = buildAudienceByCid(clientId);
                pushDTO.setAudience(audience);
                ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
                judgeResult(apiResult);
            } catch (Exception e) {
                // 个推是否成功不关心,此处异常不处理
            }
        }
    
        private PushDTO buildPushDTO(Message message) {
            if (Objects.isNull(message) || StringUtils.isEmpty(message.getTitle()) || StrUtil.isEmpty(message.getContent()) || Objects.isNull(message.getPayload())) {
                throw new IllegalArgumentException("消息不能为空!");
            }
            PushDTO pushDTO = new PushDTO();
            // 推送消息设置
            pushDTO.setRequestId(System.currentTimeMillis() + "");//requestid需要每次变化唯一
            //配置推送条件
            // 1: 表示该消息在用户在线时推送个推通道,用户离线时推送厂商通道;
            // 2: 表示该消息只通过厂商通道策略下发,不考虑用户是否在线;
            // 3: 表示该消息只通过个推通道下发,不考虑用户是否在线;
            // 4: 表示该消息优先从厂商通道下发,若消息内容在厂商通道代发失败后会从个推通道下发。
            Strategy strategy = new Strategy();
            strategy.setDef(1);
            Settings settings = new Settings();
            settings.setStrategy(strategy);
            pushDTO.setSettings(settings);
            settings.setTtl(3600000 * 12);//消息有效期,走厂商消息需要设置该值,默认12小时
            //推送苹果离线通知标题内容
            Alert alert = new Alert();
            alert.setTitle(message.getTitle());
            alert.setBody(message.getContent());
            Aps aps = new Aps();
            //1表示静默推送(无通知栏消息),静默推送时不需要填写其他参数。
            //苹果建议1小时最多推送3条静默消息
            aps.setContentAvailable(0);
            aps.setSound("default");
            aps.setAlert(alert);
            IosDTO iosDTO = new IosDTO();
            iosDTO.setAps(aps);
            iosDTO.setType("notify");
            iosDTO.setAutoBadge("+1");
            JSONObject jsonObject1 = JSONUtil.parseObj(message.getPayload());
            jsonObject1.put("alive", false);
            String s1 = jsonObject1.toString();
            iosDTO.setPayload(s1);
            PushChannel pushChannel = new PushChannel();
            pushChannel.setIos(iosDTO);
            //安卓离线厂商通道推送消息体
            AndroidDTO androidDTO = new AndroidDTO();
            Ups ups = new Ups();
            ThirdNotification notification1 = new ThirdNotification();
            ups.setNotification(notification1);
            notification1.setTitle(message.getTitle());
            notification1.setBody(message.getContent());
            notification1.setClickType("intent");
            JSONObject jsonObject = JSONUtil.parseObj(message.getPayload());
            jsonObject.put("alive", false);
            String s = jsonObject.toString();
    
    
            notification1.setIntent("intent:" +
                    "#Intent;" +
                    "launchFlags=0x04000000;" +
                    "action=android.intent.action.oppopush;" +
                    "component=" + packageName + "/io.dcloud.PandoraEntry;" +
                    "S.UP-OL-SU=true;" +
                    "S.title=" + message.getTitle() + ";" +
                    "S.content=" + message.getContent() + ";" +
                    "S.payload=" + s + ";" +
                    "end");
            //各厂商自有功能单项设置
            //ups.addOption("HW", "/message/android/notification/badge/class", "io.dcloud.PandoraEntry ");
            //ups.addOption("HW", "/message/android/notification/badge/add_num", 1);
            //ups.addOption("HW", "/message/android/notification/importance", "HIGH");
            //ups.addOption("VV","classification",1);
            androidDTO.setUps(ups);
            pushChannel.setAndroid(androidDTO);
            pushDTO.setPushChannel(pushChannel);
    
            // PushMessage在线走个推通道才会起作用的消息体
            PushMessage pushMessage = new PushMessage();
            pushDTO.setPushMessage(pushMessage);
            HashMap<String, String> transmission = Maps.newHashMap();
            transmission.put("title", message.getTitle());
            transmission.put("content", message.getContent());
            transmission.put("payload", message.getPayload());
            pushMessage.setTransmission(JSONUtil.toJsonStr(transmission));
            return pushDTO;
        }
    
        private Audience buildAudienceByCid(String clientId) {
            if (StringUtils.isBlank(clientId)) {
                throw new IllegalArgumentException("参数不合法!");
            }
            Audience audience = new Audience();
            audience.addCid(clientId);
            return audience;
        }
    
        private Boolean judgeResult(ApiResult<Map<String, Map<String, String>>> result) {
            if (Objects.isNull(result)) {
                log.error("推送结果为空!");
                return Boolean.FALSE;
            }
            if (CollectionUtils.isEmpty(result.getData())) {
                log.error("推送结果异常,code:{}, msg:{}", result.getCode(), result.getMsg());
                return Boolean.FALSE;
            }
            if (result.isSuccess()) {
                log.info("消息推送成功,code:" + result.getCode() + ", msg:" + result.getMsg());
                return Boolean.TRUE;
            } else {
                log.info("消息推送失败,code:" + result.getCode() + ", msg:" + result.getMsg());
                return Boolean.FALSE;
            }
        }
    }
    
    @Data
    public class Message {
        private String title;
        private String content;
        private String payload;
    }

  5. 在需要使用个推的地方调用相关方法:在需要使用个推功能的地方,通过依赖注入的方式引入个推的服务类,并调用相应的方法来完成推送消息、绑定用户等操作。

     PushProvider pushProvider = pushConfig.readySendMsg();
     String msg = "要推送的消息xxxx"
     // 推送APP
     Message message = new Message();
     message.setTitle("标题");
     message.setContent(msg);
     pushProvider.pushBatchByCid(cids, message);

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,下面是SpringBoot集成极光推送进行推送消息的步骤和代码示例: 1. 引入极光推送Java-SDK的依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>cn.jiguang</groupId> <artifactId>jiguang-common</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>cn.jiguang</groupId> <artifactId>jiguang-api</artifactId> <version>1.3.0</version> </dependency> ``` 2. 配置极光推送的AppKey和MasterSecret 在SpringBoot的配置文件中添加如下配置: ```properties jpush.appKey=yourAppKey jpush.masterSecret=yourMasterSecret ``` 3. 编写推送消息的代码 在需要推送消息的地方,注入JPushClient对象,然后调用JPushClient的相关方法即可实现推送消息的功能。以下是一个简单的推送消息的示例: ```java @RestController public class PushController { @Autowired private JPushClient jPushClient; @PostMapping("/push") public String pushMessage(@RequestParam("message") String message) { PushPayload payload = PushPayload.newBuilder() .setPlatform(Platform.all()) .setAudience(Audience.all()) .setNotification(Notification.alert(message)) .build(); try { PushResult result = jPushClient.sendPush(payload); return result.toString(); } catch (APIConnectionException | APIRequestException e) { e.printStackTrace(); return e.getMessage(); } } } ``` 在上述代码中,我们构建了一个PushPayload对象,设置了推送平台、推送对象和推送消息,然后调用JPushClient的sendPush方法发送推送消息。 以上就是SpringBoot集成极光推送进行推送消息的基本步骤和代码示例。希望能够对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值