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
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;
@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;
}
@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
String clientInfo = redisServiceImpl.get(UNI_PUSH_KEY_PREFIX + user.getUserId());
String[] infos = StringUtils.delimitedListToStringArray(clientInfo, "-");
if (ArrayUtil.isNotEmpty(infos) && infos.length == THREE) {
String clientId = infos[0];
String systemType = infos[1];
String appSource = infos[2];
UniPushAppsConfig.UniPushConfig uniPushConfig = uniPushAppsConfig.getApps().get(appSource);
if (ObjectUtil.isNotEmpty(uniPushConfig)) {
switch (systemType) {
case ANDROID:
UniPushUtils.singlePush(title, content, clientId, uniPushConfig);
break;
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;
@Log4j2
public class UniPushUtils {
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();
style.setTitle(title);
style.setText(content);
style.setLogo("./src/main/resources/static/push.png");
style.setLogoUrl("");
style.setRing(true);
style.setVibrate(true);
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);
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("服务器响应异常");
}
}
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);
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("服务器响应异常");
}
}
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));
return template;
}
private static APNPayload getAPNPayload(String title, String content) {
APNPayload payload = new APNPayload();
payload.setAutoBadge("+1");
payload.setContentAvailable(0);
payload.setSound("default");
payload.setCategory("$由客户端定义");
payload.addCustomMsg("由客户自定义消息key", "由客户自定义消息value");
payload.setAlertMsg(
getDictionaryAlertMsg(title, content));
return payload;
}
private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title,
String content) {
APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
alertMsg.setBody(content);
alertMsg.setTitle(title);
return alertMsg;
}
}