【SpringBoot】在SpringBoot中如何使用 极光推送

一、开通极光推送服务

跳转到极光官网:https://www.jiguang.cn/,根据官网提示开通极光推送服务。

二、编写SpringBoot程序

(一)yml配置文件

在apllication.yml中加入以下配置

jpush:
  appkey: 开发者appkey #极光官网-个人管理中心-appkey
  secret: 开发者secret #极光官网-个人管理中心-点击查看-secret

(二)config配置类

import cn.jpush.api.JPushClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**极光推送配置
 *
 * @email: pengyujun53@163.com
 * @author: peng_YuJun
 * @date: 2022/12/27
 * @time: 9:02
 */
@Configuration
public class JiGuangConfig {
    /**
     * 极光官网-个人管理中心-appkey
     * https://www.jiguang.cn/
     */
    @Value("${jpush.appkey}")
    private String appkey;

    /**
     * 极光官网-个人管理中心-点击查看-secret
     */
    @Value("${jpush.secret}")
    private String secret;


    private JPushClient jPushClient;

    /**
     * 推送客户端
     * @return
     */
    @PostConstruct
    public void initJPushClient() {
        jPushClient = new JPushClient(secret, appkey);
    }

    /**
     * 获取推送客户端
     * @return
     */
    public JPushClient getJPushClient() {
        return jPushClient;
    }
}

(三)定义极光推送的实体对象

后面主要推送的信息数据就存储在该实体中

import java.util.Map;

public class PushBean {

	// 必填, 通知内容, 内容可以为空字符串,则表示不展示到通知栏。
	private String alert;
	// 可选, 附加信息, 供业务使用。
	private Map<String, String> extras;
	//android专用// 可选, 通知标题	如果指定了,则通知里原来展示 App名称的地方,将展示成这个字段。
	private String title;

	public String getAlert() {
		return alert;
	}

	public void setAlert(String alert) {
		this.alert = alert;
	}

	public Map<String, String> getExtras() {
		return extras;
	}

	public void setExtras(Map<String, String> extras) {
		this.extras = extras;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public PushBean() {
	}

	public PushBean(String alert, Map<String, String> extras, String title) {
		this.alert = alert;
		this.extras = extras;
		this.title = title;
	}

	@Override
	public String toString() {
		return "PushBean{" +
				"alert='" + alert + '\'' +
				", extras=" + extras +
				", title='" + title + '\'' +
				'}';
	}
}

(四)servcie服务类

后面调用极光的推送功能,都是调用此处的方法

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
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.Notification;
import com.example.gascheck.config.JiGuangConfig;
import com.example.gascheck.pojo.PushBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @email: pengyujun53@163.com
 * @author: peng_YuJun
 * @date: 2022/12/27
 * @time: 9:25
 */
@Slf4j
@Service
public class JiGuangPushService {
    /** 一次推送最大数量 (极光限制1000) */
    private static final int max_size = 800;

    @Autowired
    private JiGuangConfig jPushConfig;


    /**
     * 广播 (所有平台,所有设备, 不支持附加信息)
     * @return
     */
    public boolean pushAll(PushBean pushBean){
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(Notification.alert(pushBean.getAlert()))
                .build());
    }

    /**
     * 推送全部ios ios广播
     * @return
     */
    public boolean pushIos(PushBean pushBean){
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.all())
                .setNotification(Notification.ios(pushBean.getAlert(), pushBean.getExtras()))
                .build());
    }

    /**
     * 推送ios 指定id
     * @return
     */
    public boolean pushIos(PushBean pushBean, String... registids){
        registids = checkRegistids(registids); // 剔除无效registed
        while (registids.length > max_size) { // 每次推送max_size个
            sendPush(PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.registrationId(Arrays.copyOfRange(registids, 0, max_size)))
                    .setNotification(Notification.ios(pushBean.getAlert(), pushBean.getExtras()))
                    .build());
            registids = Arrays.copyOfRange(registids, max_size, registids.length);
        }
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.registrationId(Arrays.copyOfRange(registids, 0, max_size)))
                .setNotification(Notification.ios(pushBean.getAlert(), pushBean.getExtras()))
                .build());
    }

    /**
     * 推送全部android
     * @return
     */
    public boolean pushAndroid(PushBean pushBean){
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.all())
                .setNotification(Notification.android(pushBean.getAlert(), pushBean.getTitle(), pushBean.getExtras()))
                .build());
    }

    /**
     * 推送android 指定id
     * @return
     */
    public boolean pushAndroid(PushBean pushBean, String... registids){
        registids = checkRegistids(registids); // 剔除无效registed
        while (registids.length > max_size) { // 每次推送max_size个
            sendPush(PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.registrationId(Arrays.copyOfRange(registids, 0, max_size)))
                    .setNotification(Notification.android(pushBean.getAlert(), pushBean.getTitle(), pushBean.getExtras()))
                    .build());
            registids = Arrays.copyOfRange(registids, max_size, registids.length);
        }
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.registrationId(registids))
                .setNotification(Notification.android(pushBean.getAlert(), pushBean.getTitle(), pushBean.getExtras()))
                .build());
    }

    /**
     * 剔除无效registed
     * @param registids
     * @return
     */
    public String[] checkRegistids(String[] registids) {
        List<String> regList = new ArrayList<String>(registids.length);
        for (String registid : registids) {
            if (registid!=null && !"".equals(registid.trim())) {
                regList.add(registid);
            }
        }
        return regList.toArray(new String[0]);
    }

    /**
     * 调用api推送
     * @param pushPayload 推送实体
     * @return
     */
    public boolean sendPush(PushPayload pushPayload){
        PushResult result = null;
        try{
            result = jPushConfig.getJPushClient().sendPush(pushPayload);
        } catch (APIConnectionException e) {
            log.error("极光推送连接异常: ", e);
        } catch (APIRequestException e) {
            log.error("极光推送请求异常: ", e);
        }
        if (result!=null && result.isResultOK()) {
            log.info("极光推送请求成功: {}", result);
            return true;
        }else {
            log.info("极光推送请求失败: {}", result);
            return false;
        }
    }
}

(五)调用极光推送服务示例

@Resource
private JiGuangPushService jiGuangService; //注入极光推送服务类对象

//具体用到推送服务的方法就可以用以下程序实现

//定义和赋值推送实体
PushBean pushBean = new PushBean();
pushBean.setTitle("titleStr");
pushBean.setAlert("alertStr");
//额外推送信息
Map<String,String> map = new HashMap<>();
map.put("xxx","xxx");
pushBean.setExtras(map); 
//进行推送,推送到所有使用Android客户端的用户,返回推送结果布尔值
boolean flag = jiGuangService.pushAndroid(pushBean);
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要在Spring Boot使用极光推送服务,你需要进行以下几个步骤。 1. 首先,你需要在极光官网(https://www.jiguang.cn/)进行注册并开通极光推送服务。 2. 然后,在你的Spring Boot程序,创建一个yml配置文件,用于配置推送服务的相关信息。 3. 在程序引入极光推送的服务类,并注入到需要使用的地方。你可以使用@Autowired注解将JiGuangPushService注入到你的控制器。 4. 如果你想进行广播推送,即给所有拥有你的app下载安装的用户发送推送消息,你可以使用pushAll方法。该方法接收推送标题和内容作为参数,并返回一个布尔值表示推送是否成功。 5. 如果你想进行单点推送,即给指定的用户发送推送消息,你可以使用push方法。该方法接收推送标题、设备对应的唯一极光ID(regId)和推送内容作为参数,并返回一个布尔值表示推送是否成功。 通过以上步骤,你可以在Spring Boot使用极光推送服务来发送推送消息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [【SpringBoot】在SpringBoot如何使用 极光推送](https://blog.csdn.net/peng_YuJun/article/details/130163389)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [SpringBoot整合极光推送](https://blog.csdn.net/qq_39252591/article/details/105224791)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

peng_YuJun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值