JAVA uni-push

java后台UniPush的实现流程与写法

依赖

		
		<dependency>
			<groupId>com.gexin.platformgroupId>
			<artifactId>gexin-rp-sdk-httpartifactId>
			<version>4.1.2.0version>
		dependency>
	<repositories>
		<repository>
			<id>getui-nexusid>
			<url>http://mvn.gt.getui.com/nexus/content/repositories/releases/url>
		repository>
	repositories>

nacos

  # 一般只需要配置app-id、app-key、master-secret
  # url 为固定地址
unipush:
  apps:
    merchant:
      app-id: YLxcN0xoey7U7pRVr6Qi89
      app-key: 44uDj49EFB7dr4aupiFjcA
      master-secret: ne7y5u36848NIK34YUpFb2
      url: http://api.getui.com/apiex.htm
      

配置

package test.common.core.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自己根据业务需求取配置相关信息
 */

@Data
@Configuration
@Component
@ConfigurationProperties(prefix = "unipush")
public class UniPushAppsConfig {

	private Map<String, UniPushConfig> apps = new LinkedHashMap<>();

	@Data
	public static class UniPushConfig {
		private String appId;
		private String appKey;
		private String masterSecret;
		private String url;
	}
}

Controller

package test.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/message")
@Api(value = "message", tags = "消息")
public class MessageController {

	@Autowired
	private StringRedisTemplate redisTemplate;


	/**
	 * * 存储client信息
	 * * APP用户登录系统时调用
	 *
	 * @param userId     用户id
	 * @param clientInfo 自定义client信息
	 * @return Boolean
	 */
	@ApiOperation(value = "存储clientInfo")
	@PostMapping("/save-client-info")
	public Boolean saveClientInfoToRedis(Integer userId, String clientInfo) {
		String key = UNI_PUSH_KEY_PREFIX + userId;
		redisTemplate.opsForValue().set(key, clientInfo);
		return Boolean.TRUE;
	}


	/**
	 * 清除client信息
	 *
	 * @param userId 用户id
	 * @return Boolean
	 */
	@ApiOperation(value = "清除clientInfo")
	@DeleteMapping("/remove-client-info")
	public Boolean removeClientInfoForRedis(Integer userId) {
		String key = UNI_PUSH_KEY_PREFIX + userId;
		redisTemplate.delete(key);
		return Boolean.TRUE;
	}
}

Service


	/**
	 * 业务处理根据自己的需求来写,
	 * 先根据用户取得Redis里缓存信息,前端用户登陆app时调接口储存的自定义信息clientInfo (clientId、系统类型、程序来源,具体想存什么根据自己业务),
	 * 然后获取提前配置在nacos上的配置信息,
	 * 再根据不同的系统类型(android、ios)调用不同的工具类方法
	 */
		// 发送个推消息
		String clientInfo = redisServiceImpl.get(UNI_PUSH_KEY_PREFIX + user.getUserId());
		String[] infos = StringUtils.delimitedListToStringArray(clientInfo, "-");
		if (ArrayUtil.isNotEmpty(infos) && infos.length == THREE) {
			// app clientId
			String clientId = infos[0];
			// 系统类型
			String systemType = infos[1];
			// 程序来源
			String appSource = infos[2];
			// 取得uni-push配置信息
			UniPushAppsConfig.UniPushConfig uniPushConfig = uniPushAppsConfig.getApps().get(appSource);
			if (ObjectUtil.isNotEmpty(uniPushConfig)) {
				switch (systemType) {
					// 安卓
					case ANDROID:
						UniPushUtils.singlePush(title, content, clientId, uniPushConfig);
						break;
					// ios
					case IOS:
						UniPushUtils.singlePushForIOS(title, content, clientId, uniPushConfig);
						break;
				}
			} else {
				// 无配置信息
				log.error("Not config unipush for client [{}]", appSource);
			}
		}

工具类

package test.common.core.util;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.Constants;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import test.common.core.config.UniPushAppsConfig.UniPushConfig;
import lombok.extern.log4j.Log4j2;

/**
 * uni-push 工具类
 *
 * @author kelvins
 */
@Log4j2
public class UniPushUtils {

	/**
	 * 单消息推送(安卓)
	 *
	 * @param title         标题
	 * @param content       内容
	 * @param clientId      推送者clientId
	 * @param uniPushConfig unipush配置信息
	 */
	public static void singlePush(String title, String content, String clientId,
								  UniPushConfig uniPushConfig) {
		System.setProperty(Constants.GEXIN_PUSH_SINGLE_ALIAS_DETAIL, "true");
		IGtPush push = new IGtPush(uniPushConfig.getUrl(), uniPushConfig.getAppKey(),
				uniPushConfig.getMasterSecret());
		log.info("unipush info(title - content - clientId) [{}] - [{}] - [{}]", title,
				content, clientId);
		log.info("unipush config data. {}", JsonUtil.toJson(uniPushConfig));

		Style0 style = new Style0();
		// STEP2:设置推送标题、推送内容
		style.setTitle(title);
		style.setText(content);
		// 设置推送图标
		style.setLogo("./src/main/resources/static/push.png");
		// 配置通知栏网络图标
		style.setLogoUrl("");
		// STEP3:设置响铃、震动等推送效果
		// 设置响铃
		style.setRing(true);
		// 设置震动
		style.setVibrate(true);

		// STEP4:选择通知模板
		NotificationTemplate template = new NotificationTemplate();
		template.setTransmissionType(1);
		template.setAppId(uniPushConfig.getAppId());
		template.setAppkey(uniPushConfig.getAppKey());
		template.setStyle(style);

		SingleMessage message = new SingleMessage();
		message.setOffline(true);
		// 离线有效时间,单位为毫秒
		message.setOfflineExpireTime(24 * 3600 * 1000);
		message.setData(template);
		// 可选,1为wifi,0为不限制网络环境。根据手机处于的网络情况,决定是否下发
		message.setPushNetWorkType(0);

		Target target = new Target();
		target.setAppId(uniPushConfig.getAppId());
		target.setClientId(clientId);

		IPushResult ret = null;
		try {
			ret = push.pushMessageToSingle(message, target);
		} catch (RequestException e) {
			System.out.println(e.getMessage());
			ret = push.pushMessageToSingle(message, target, e.getRequestId());
		}
		if (ret != null) {
			log.info("unipush result." + ret.getResponse().toString());
		} else {
			log.error("服务器响应异常");
		}
	}

	/**
	 * 单消息推送(IOS)
	 *
	 * @param title         标题
	 * @param content       内容
	 * @param clientId      推送者clientId
	 * @param uniPushConfig unipush配置信息
	 */
	public static void singlePushForIOS(String title, String content, String clientId,
										UniPushConfig uniPushConfig) {
		System.setProperty(Constants.GEXIN_PUSH_SINGLE_ALIAS_DETAIL, "true");
		IGtPush push = new IGtPush(uniPushConfig.getUrl(), uniPushConfig.getAppKey(),
				uniPushConfig.getMasterSecret());
		log.info("unipush info(title - content - clientId) [{}] - [{}] - [{}]", title,
				content, clientId);
		log.info("unipush config data. {}", JsonUtil.toJson(uniPushConfig));
		TransmissionTemplate transmissionTemplate = transmissionTemplateDemo(title, content,
				uniPushConfig.getAppId(),
				uniPushConfig.getAppKey());

		SingleMessage message = new SingleMessage();
		message.setOffline(true);
		// 离线有效时间,单位为毫秒
		message.setOfflineExpireTime(24 * 3600 * 1000);
		message.setData(transmissionTemplate);
		// 可选,1为wifi,0为不限制网络环境。根据手机处于的网络情况,决定是否下发
		message.setPushNetWorkType(0);
		// 厂商通道下发策略
		message.setStrategyJson("{\"default\":4,\"ios\":4,\"st\":4}");

		Target target = new Target();
		target.setAppId(uniPushConfig.getAppId());
		target.setClientId(clientId);

		IPushResult ret = null;
		try {
			ret = push.pushMessageToSingle(message, target);
		} catch (RequestException e) {
			e.printStackTrace();
			ret = push.pushMessageToSingle(message, target, e.getRequestId());
		}
		if (ret != null) {
			log.info("uni-push result." + ret.getResponse().toString());
		} else {
			log.error("服务器响应异常");
		}
	}

	/**
	 * 取得IOS透传消息模板
	 *
	 * @param title   消息标题
	 * @param content 消息内容
	 * @return
	 */
	public static TransmissionTemplate transmissionTemplateDemo(String title, String content,
																String APPID, String APPKEY) {
		TransmissionTemplate template = new TransmissionTemplate();
		template.setAppId(APPID);
		template.setAppkey(APPKEY);
		template.setTransmissionType(2);
		template.setTransmissionContent(content);
		template.setAPNInfo(getAPNPayload(title, content)); //详见本页iOS通知样式设置
		return template;
	}

	/**
	 * 取得IOS透传消息配置
	 *
	 * @param title   消息标题
	 * @param content 消息内容
	 * @return
	 */
	private static APNPayload getAPNPayload(String title, String content) {
		APNPayload payload = new APNPayload();
		//在已有数字基础上加1显示,设置为-1时,在已有数字上减1显示,设置为数字时,显示指定数字
		payload.setAutoBadge("+1");
		payload.setContentAvailable(0);
		//ios 12.0 以上可以使用 Dictionary 类型的 sound
		payload.setSound("default");
		payload.setCategory("$由客户端定义");
		payload.addCustomMsg("由客户自定义消息key", "由客户自定义消息value");

		//简单模式APNPayload.SimpleMsg
		//payload.setAlertMsg(new APNPayload.SimpleAlertMsg("hello"));
		payload.setAlertMsg(
				getDictionaryAlertMsg(title, content));  //字典模式使用APNPayload.DictionaryAlertMsg
		return payload;
	}

	/**
	 * IOS自定义消息标题和内容
	 *
	 * @param title   消息标题
	 * @param content 消息内容
	 * @return
	 */
	private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title,
																	   String content) {
		APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
		// 设置通知内容
		alertMsg.setBody(content);
		// 设置通知标题
		alertMsg.setTitle(title);
		return alertMsg;
	}
}

你可能感兴趣的:(java,spring,开发语言)