当前位置:   article > 正文

个推消息推送SDK快速Springboot项目集成案例_个推java sdk使用

个推java sdk使用

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

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

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

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

  1. 用户登陆手机 将clientid和用户id绑定
    1. @Autowired
    2. private ClientInfoService clientInfoService;
    3. @ApiOperation(value = "用户绑定")
    4. @PostMapping("/bind")
    5. public ApiResult submit(@RequestBody ClientInfoBindDTO bindDTO) {
    6. this.clientInfoService.bind(bindDTO);
    7. return R.success("操作成功");
    8. }
    9. @Service
    10. public class ClientInfoServiceImpl extends ServiceImpl<ClientInfoMapper, ClientInfo> implements ClientInfoService{
    11. @Override
    12. public void bind(ClientInfoBindDTO bindDTO) {
    13. ClientInfo one = this.getOne(new LambdaQueryWrapper<ClientInfo>().eq(ClientInfo::getUserId, bindDTO.getUserId()).eq(ClientInfo::getPlatform, bindDTO.getPlatform()));
    14. ClientInfo clientInfo = ModelMapper.map(bindDTO, ClientInfo.class);
    15. if (one == null) {
    16. this.save(clientInfo);
    17. } else {
    18. if (!one.getCid().equals(bindDTO.getCid())) {
    19. // 更新CID
    20. clientInfo.setId(one.getId());
    21. this.updateById(clientInfo);
    22. }
    23. }
    24. }
    25. }
    26. /**
    27. * app消息推送表
    28. * @TableName spang_client_info
    29. */
    30. @TableName(value ="spang_client_info")
    31. @Data
    32. public class ClientInfo implements Serializable {
    33. private static final long serialVersionUID = 1L;
    34. /**
    35. * 主键
    36. */
    37. @JsonSerialize(using = ToStringSerializer.class)
    38. @ApiModelProperty(value = "主键id")
    39. @TableId(value = "id", type = IdType.ASSIGN_ID)
    40. private Long id;
    41. /**
    42. * 用户主键ID
    43. */
    44. @TableField(value = "user_id")
    45. private Long userId;
    46. /**
    47. * 推送使用的clientId
    48. */
    49. @TableField(value = "cid")
    50. private String cid;
    51. /**
    52. * 所属平台
    53. */
    54. @TableField(value = "platform")
    55. private String platform;
    56. /**
    57. * 别名
    58. */
    59. @TableField(value = "alias")
    60. private String alias;
    61. /**
    62. * 城市
    63. */
    64. @TableField(value = "city")
    65. private String city;
    66. }
    67. @Data
    68. @ApiModel(description = "绑定系统用户与个推用户的clientId")
    69. public class ClientInfoBindDTO implements Serializable {
    70. private static final long serialVersionUID = 1L;
    71. @ApiModelProperty(value = "用户主键ID")
    72. private Long userId;
    73. @ApiModelProperty(value = "个推对应的用户客户端ID")
    74. private String cid;
    75. @ApiModelProperty(value = "个推对应的用户客户端平台类型")
    76. private String platform;
    77. }
    78. DROP TABLE IF EXISTS `spang_client_info`;
    79. CREATE TABLE `spang_client_info` (
    80. `id` bigint(20) NOT NULL COMMENT '主键',
    81. `user_id` bigint(20) NOT NULL COMMENT '用户主键ID',
    82. `cid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '推送使用的clientId',
    83. `platform` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '所属平台',
    84. `alias` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '别名',
    85. `city` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '城市',
    86. PRIMARY KEY (`id`) USING BTREE
    87. ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = 'app消息推送表' ROW_FORMAT = Dynamic;

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

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

    1. /**
    2. app:
    3. appId: xxxxx
    4. appKey: xxxxx
    5. masterSecret: xxxxxx
    6. packageName: xxxxxxx
    7. **/
    8. @Data
    9. @Configuration
    10. @ConfigurationProperties(prefix = "app")
    11. public class PushConfig {
    12. public String appId;
    13. public String appKey;
    14. public String masterSecret;
    15. public String packageName;
    16. private PushProvider pushProvider;
    17. /**
    18. * 个推获取初始化信息
    19. *
    20. * @param
    21. * @return com.spang.emergency.service.PushProvider
    22. */
    23. public PushProvider getPushProvider() {
    24. if (this.pushProvider == null) {
    25. pushProvider = new PushProvider(appId, appKey, masterSecret, packageName);
    26. } else {
    27. pushProvider.refreshApi();
    28. }
    29. return pushProvider;
    30. }
    31. public PushProvider readySendMsg() {
    32. return pushProvider;
    33. }
    34. }
  4. 创建个推的服务类:创建一个 Java 类,用于封装个推相关的操作。在该类中,注入配置文件中的参数,并实现推送消息、绑定用户等个推功能的方法。

    1. import cn.hutool.core.util.StrUtil;
    2. import cn.hutool.json.JSONObject;
    3. import cn.hutool.json.JSONUtil;
    4. import com.getui.push.v2.sdk.ApiHelper;
    5. import com.getui.push.v2.sdk.GtApiConfiguration;
    6. import com.getui.push.v2.sdk.api.PushApi;
    7. import com.getui.push.v2.sdk.api.UserApi;
    8. import com.getui.push.v2.sdk.common.ApiResult;
    9. import com.getui.push.v2.sdk.dto.req.*;
    10. import com.getui.push.v2.sdk.dto.req.message.PushBatchDTO;
    11. import com.getui.push.v2.sdk.dto.req.message.PushChannel;
    12. import com.getui.push.v2.sdk.dto.req.message.PushDTO;
    13. import com.getui.push.v2.sdk.dto.req.message.PushMessage;
    14. import com.getui.push.v2.sdk.dto.req.message.android.AndroidDTO;
    15. import com.getui.push.v2.sdk.dto.req.message.android.ThirdNotification;
    16. import com.getui.push.v2.sdk.dto.req.message.android.Ups;
    17. import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
    18. import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
    19. import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
    20. import com.google.common.collect.Maps;
    21. import lombok.extern.slf4j.Slf4j;
    22. import org.apache.commons.lang.StringUtils;
    23. import org.springframework.util.CollectionUtils;
    24. import java.util.*;
    25. @Slf4j
    26. public class PushProvider {
    27. private String appId;
    28. private String appKey;
    29. private String masterSecret;
    30. private String packageName;
    31. private ApiHelper apiHelper;
    32. private static PushApi pushApi;
    33. private static UserApi userApi;
    34. public PushProvider(String appId, String appKey, String masterSecret, String packageName) {
    35. this.appId = appId;
    36. this.appKey = appKey;
    37. this.masterSecret = masterSecret;
    38. this.packageName = packageName;
    39. GtApiConfiguration apiConfiguration = new GtApiConfiguration();
    40. //填写应用配置
    41. apiConfiguration.setAppId(appId);
    42. apiConfiguration.setAppKey(appKey);
    43. apiConfiguration.setMasterSecret(masterSecret);
    44. // 实例化ApiHelper对象,用于创建接口对象
    45. apiHelper = ApiHelper.build(apiConfiguration);
    46. pushApi = apiHelper.creatApi(PushApi.class);
    47. userApi = apiHelper.creatApi(UserApi.class);
    48. }
    49. /**
    50. * 配置数据有变化,则刷新个推api认证信息
    51. */
    52. public void refreshApi() {
    53. GtApiConfiguration apiConfiguration = new GtApiConfiguration();
    54. //填写应用配置
    55. apiConfiguration.setAppId(appId);
    56. apiConfiguration.setAppKey(appKey);
    57. apiConfiguration.setMasterSecret(masterSecret);
    58. // 实例化ApiHelper对象,用于创建接口对象
    59. apiHelper = ApiHelper.build(apiConfiguration);
    60. pushApi = apiHelper.creatApi(PushApi.class);
    61. userApi = apiHelper.creatApi(UserApi.class);
    62. }
    63. /**
    64. * 个推批量推送
    65. */
    66. public void pushBatchByCid(List<String> clientIds, Message message) {
    67. try {
    68. if (CollectionUtils.isEmpty(clientIds)) {
    69. return;
    70. }
    71. PushBatchDTO pushBatchDTO = new PushBatchDTO();
    72. List<PushDTO<Audience>> msgList = new ArrayList<>(clientIds.size());
    73. for (String clientId : clientIds) {
    74. PushDTO<Audience> pushDTO = buildPushDTO(message);
    75. pushDTO.setAudience(buildAudienceByCid(clientId));
    76. msgList.add(pushDTO);
    77. }
    78. pushBatchDTO.setAsync(true);
    79. pushBatchDTO.setMsgList(msgList);
    80. ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushBatchByCid(pushBatchDTO);
    81. judgeResult(apiResult);
    82. } catch (Exception e) {
    83. // 个推是否成功不关心,此处异常不处理
    84. }
    85. }
    86. /**
    87. * 个推单人推送
    88. * @param clientId
    89. * @param message
    90. * @return java.lang.Boolean
    91. */
    92. public void pushToSingleByCid(String clientId, Message message) {
    93. try {
    94. PushDTO<Audience> pushDTO = buildPushDTO(message);
    95. Audience audience = buildAudienceByCid(clientId);
    96. pushDTO.setAudience(audience);
    97. ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
    98. judgeResult(apiResult);
    99. } catch (Exception e) {
    100. // 个推是否成功不关心,此处异常不处理
    101. }
    102. }
    103. private PushDTO buildPushDTO(Message message) {
    104. if (Objects.isNull(message) || StringUtils.isEmpty(message.getTitle()) || StrUtil.isEmpty(message.getContent()) || Objects.isNull(message.getPayload())) {
    105. throw new IllegalArgumentException("消息不能为空!");
    106. }
    107. PushDTO pushDTO = new PushDTO();
    108. // 推送消息设置
    109. pushDTO.setRequestId(System.currentTimeMillis() + "");//requestid需要每次变化唯一
    110. //配置推送条件
    111. // 1: 表示该消息在用户在线时推送个推通道,用户离线时推送厂商通道;
    112. // 2: 表示该消息只通过厂商通道策略下发,不考虑用户是否在线;
    113. // 3: 表示该消息只通过个推通道下发,不考虑用户是否在线;
    114. // 4: 表示该消息优先从厂商通道下发,若消息内容在厂商通道代发失败后会从个推通道下发。
    115. Strategy strategy = new Strategy();
    116. strategy.setDef(1);
    117. Settings settings = new Settings();
    118. settings.setStrategy(strategy);
    119. pushDTO.setSettings(settings);
    120. settings.setTtl(3600000 * 12);//消息有效期,走厂商消息需要设置该值,默认12小时
    121. //推送苹果离线通知标题内容
    122. Alert alert = new Alert();
    123. alert.setTitle(message.getTitle());
    124. alert.setBody(message.getContent());
    125. Aps aps = new Aps();
    126. //1表示静默推送(无通知栏消息),静默推送时不需要填写其他参数。
    127. //苹果建议1小时最多推送3条静默消息
    128. aps.setContentAvailable(0);
    129. aps.setSound("default");
    130. aps.setAlert(alert);
    131. IosDTO iosDTO = new IosDTO();
    132. iosDTO.setAps(aps);
    133. iosDTO.setType("notify");
    134. iosDTO.setAutoBadge("+1");
    135. JSONObject jsonObject1 = JSONUtil.parseObj(message.getPayload());
    136. jsonObject1.put("alive", false);
    137. String s1 = jsonObject1.toString();
    138. iosDTO.setPayload(s1);
    139. PushChannel pushChannel = new PushChannel();
    140. pushChannel.setIos(iosDTO);
    141. //安卓离线厂商通道推送消息体
    142. AndroidDTO androidDTO = new AndroidDTO();
    143. Ups ups = new Ups();
    144. ThirdNotification notification1 = new ThirdNotification();
    145. ups.setNotification(notification1);
    146. notification1.setTitle(message.getTitle());
    147. notification1.setBody(message.getContent());
    148. notification1.setClickType("intent");
    149. JSONObject jsonObject = JSONUtil.parseObj(message.getPayload());
    150. jsonObject.put("alive", false);
    151. String s = jsonObject.toString();
    152. notification1.setIntent("intent:" +
    153. "#Intent;" +
    154. "launchFlags=0x04000000;" +
    155. "action=android.intent.action.oppopush;" +
    156. "component=" + packageName + "/io.dcloud.PandoraEntry;" +
    157. "S.UP-OL-SU=true;" +
    158. "S.title=" + message.getTitle() + ";" +
    159. "S.content=" + message.getContent() + ";" +
    160. "S.payload=" + s + ";" +
    161. "end");
    162. //各厂商自有功能单项设置
    163. //ups.addOption("HW", "/message/android/notification/badge/class", "io.dcloud.PandoraEntry ");
    164. //ups.addOption("HW", "/message/android/notification/badge/add_num", 1);
    165. //ups.addOption("HW", "/message/android/notification/importance", "HIGH");
    166. //ups.addOption("VV","classification",1);
    167. androidDTO.setUps(ups);
    168. pushChannel.setAndroid(androidDTO);
    169. pushDTO.setPushChannel(pushChannel);
    170. // PushMessage在线走个推通道才会起作用的消息体
    171. PushMessage pushMessage = new PushMessage();
    172. pushDTO.setPushMessage(pushMessage);
    173. HashMap<String, String> transmission = Maps.newHashMap();
    174. transmission.put("title", message.getTitle());
    175. transmission.put("content", message.getContent());
    176. transmission.put("payload", message.getPayload());
    177. pushMessage.setTransmission(JSONUtil.toJsonStr(transmission));
    178. return pushDTO;
    179. }
    180. private Audience buildAudienceByCid(String clientId) {
    181. if (StringUtils.isBlank(clientId)) {
    182. throw new IllegalArgumentException("参数不合法!");
    183. }
    184. Audience audience = new Audience();
    185. audience.addCid(clientId);
    186. return audience;
    187. }
    188. private Boolean judgeResult(ApiResult<Map<String, Map<String, String>>> result) {
    189. if (Objects.isNull(result)) {
    190. log.error("推送结果为空!");
    191. return Boolean.FALSE;
    192. }
    193. if (CollectionUtils.isEmpty(result.getData())) {
    194. log.error("推送结果异常,code:{}, msg:{}", result.getCode(), result.getMsg());
    195. return Boolean.FALSE;
    196. }
    197. if (result.isSuccess()) {
    198. log.info("消息推送成功,code:" + result.getCode() + ", msg:" + result.getMsg());
    199. return Boolean.TRUE;
    200. } else {
    201. log.info("消息推送失败,code:" + result.getCode() + ", msg:" + result.getMsg());
    202. return Boolean.FALSE;
    203. }
    204. }
    205. }
    1. @Data
    2. public class Message {
    3. private String title;
    4. private String content;
    5. private String payload;
    6. }

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/274561
推荐阅读
相关标签
  

闽ICP备14008679号