Commit 9db856f7 authored by huangcb's avatar huangcb

新增消息推送功能接口

parent 8c45efe3
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
<spring-cloud.version>Greenwich.SR1</spring-cloud.version> <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
<alibaba-nacos-discovery.version>2.1.1.RELEASE</alibaba-nacos-discovery.version> <alibaba-nacos-discovery.version>2.1.1.RELEASE</alibaba-nacos-discovery.version>
<alibaba-nacos-config.version>2.1.1.RELEASE</alibaba-nacos-config.version> <alibaba-nacos-config.version>2.1.1.RELEASE</alibaba-nacos-config.version>
<alibaba-fastjson.version>1.2.62</alibaba-fastjson.version> <alibaba-fastjson.version>1.2.70</alibaba-fastjson.version>
<alibaba-druid.version>1.1.22</alibaba-druid.version> <alibaba-druid.version>1.1.22</alibaba-druid.version>
<apache-commons-lang3.version>3.7</apache-commons-lang3.version> <apache-commons-lang3.version>3.7</apache-commons-lang3.version>
<mybatisplus.version>3.3.1</mybatisplus.version> <mybatisplus.version>3.3.1</mybatisplus.version>
...@@ -107,6 +107,10 @@ ...@@ -107,6 +107,10 @@
<artifactId>druid-spring-boot-starter</artifactId> <artifactId>druid-spring-boot-starter</artifactId>
<version>${alibaba-druid.version}</version> <version>${alibaba-druid.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies> </dependencies>
<dependencyManagement> <dependencyManagement>
......
package com.esv.freight.notice.common.constants;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.common.constants.CommonConstants
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 11:32
* @version:1.0
*/
public class CommonConstants {
/**
* 访问端来源:1-浏览器端、2-Android端、3-iOS端、4-后台服务端
**/
public static final String REQ_SOURCE_TYPE_KEY = "Source-Type";
public static final String REQ_SOURCE_TYPE_WEB = "1";
public static final String REQ_SOURCE_TYPE_ANDROID = "2";
public static final String REQ_SOURCE_TYPE_IOS = "3";
public static final String REQ_SOURCE_TYPE_SERVICE = "4";
/**
* Feign调用返回参数
**/
public static final String FEIGN_RESULT_CODE = "code";
public static final String FEIGN_RESULT_MESSAGE = "message";
public static final String FEIGN_RESULT_DATA = "data";
public static final int FEIGN_RESULT_SUCCESS = 200;
/**
* 字符串"null"
**/
public static final String NULL_STRING = "null";
/**
* 字符串"unknown"
**/
public static final String UNKNOWN_STRING = "unknown";
/**
* log日志输出的最大长度及截取输出的长度
**/
public static final int LOG_MAX_LENGTH = 5000;
public static final int LOG_CUT_LENGTH = 1000;
/**
* Spring Boot Admin监控url前缀
**/
public static final String SPRING_BOOT_ADMIN_PREFIX_URL = "/actuator";
/**
* 默认字符编码
**/
public static final String DEFAULT_CHARACTER_ENCODING = "utf-8";
/**
* Http请求方式
**/
public static final String HTTP_REQUEST_METHOD_GET = "GET";
public static final String HTTP_REQUEST_METHOD_POST = "POST";
/**
* Http请求头
**/
public static final String HTTP_HEADER_X_FORWARDED_FOR = "x-forwarded-for";
public static final String HTTP_HEADER_PROXY_CLIENT_IP = "Proxy-Client-IP";
public static final String HTTP_HEADER_WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
}
package com.esv.freight.notice.common.util;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.notice.common.constants.CommonConstants;
import com.esv.freight.notice.common.exception.EException;
import lombok.extern.slf4j.Slf4j;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.common.util.FeignUtils
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 11:32
* @version:1.0
*/
@Slf4j
public class FeignUtils {
/**
* description 获取Feign调用结果数据
* param [resultJson]
* return com.alibaba.fastjson.JSONObject
* author Administrator
* createTime 2020/04/17 18:12
**/
public static JSONObject getFeignResultData(JSONObject resultJson) throws EException {
String result = resultJson.toJSONString();
if (CommonConstants.LOG_MAX_LENGTH < result.length()) {
result = result.substring(0, CommonConstants.LOG_CUT_LENGTH) + "……";
}
log.info(result);
if (CommonConstants.FEIGN_RESULT_SUCCESS == resultJson.getIntValue(CommonConstants.FEIGN_RESULT_CODE)) {
return resultJson.getJSONObject(CommonConstants.FEIGN_RESULT_DATA);
} else {
throw new EException(resultJson.getIntValue(CommonConstants.FEIGN_RESULT_CODE), resultJson.getString(CommonConstants.FEIGN_RESULT_MESSAGE));
}
}
}
package com.esv.freight.notice.common.util;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.*;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import javax.net.ssl.SSLContext;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Map;
@Slf4j
public class HttpUtils {
/**
* 从连接池中获取连接的超时时间(单位:毫秒)
*/
public static final int CONNECTION_REQUEST_TIMEOUT_DEFAULT = 1000;
/**
* 与服务器连接超时时间(单位:毫秒):httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间
*/
public static final int CONNECT_TIMEOUT_DEFAULT = 3000;
public static final int CONNECT_TIMEOUT_10 = 10000;
/**
* socket读数据超时时间(单位:毫秒):从服务器获取响应数据的超时时间
*/
public static final int SOCKET_TIMEOUT_DEFAULT = 2000;
public static String get(String url) throws Exception {
return get(url, null);
}
public static String get(String url, Map<String, String> headerMap) throws Exception {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_DEFAULT);
int connectTimeout = CONNECT_TIMEOUT_DEFAULT;
factory.setConnectTimeout(connectTimeout);
factory.setReadTimeout(SOCKET_TIMEOUT_DEFAULT);
RestTemplate restTemplate = new RestTemplate(factory);
// 特殊字符处理
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = builder.build().encode().toUri();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
// 设置Header
if (null != headerMap) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
headers.set(entry.getKey(), entry.getValue());
}
}
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
return result.getBody();
}
public static String post(String url, JSONObject bodyJson) {
return post(url, null, bodyJson);
}
public static String post(String url, Map<String, String> headerMap, JSONObject bodyJson) {
log.info("url:{}", url);
log.info("headerMap:{}", headerMap.toString());
log.info("body:{}", bodyJson.toJSONString());
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_DEFAULT);
int connectTimeout = CONNECT_TIMEOUT_DEFAULT;
factory.setConnectTimeout(connectTimeout);
factory.setReadTimeout(SOCKET_TIMEOUT_DEFAULT);
RestTemplate restTemplate = new RestTemplate(factory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
// 设置Header
if (null != headerMap) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
headers.set(entry.getKey(), entry.getValue());
}
}
HttpEntity<String> requestEntity = new HttpEntity<>(bodyJson.toString(), headers);
String result = restTemplate.postForObject(url, requestEntity, String.class);
log.info("response:{}", result);
return result;
}
private static CloseableHttpClient createSSLInsecureClient() {
int connectTimeout = CONNECT_TIMEOUT_DEFAULT;
return createSSLInsecureClient(CONNECTION_REQUEST_TIMEOUT_DEFAULT, connectTimeout, SOCKET_TIMEOUT_DEFAULT);
}
private static CloseableHttpClient createSSLInsecureClient(int connectionRequestTimeout, int connectTimeout, int socketTimeout) {
CookieStore cookieStore = new BasicCookieStore();
RequestConfig requestConfig = RequestConfig.custom()
// 从连接池中获取连接的超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)
// 与服务器连接超时时间:httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间
.setConnectTimeout(connectTimeout)
// socket读数据超时时间:从服务器获取响应数据的超时时间
.setSocketTimeout(socketTimeout)
.build();
try {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, new TrustStrategy() {
//信任所有
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.setRedirectStrategy(new DefaultRedirectStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore)
.build();
} catch (KeyManagementException e) {
log.error(e.getMessage(), ThrowableUtils.toString(e));
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), ThrowableUtils.toString(e));
} catch (KeyStoreException e) {
log.error(e.getMessage(), ThrowableUtils.toString(e));
}
return HttpClients.createDefault();
}
}
package com.esv.freight.notice.common.util;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* @description: 异常工具类
* @project: freight-notice-service
* @name: com.esv.freight.notice.common.util.ThrowableUtils
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 17:15
* @version:1.0
*/
public class ThrowableUtils {
/**
* description 获取异常输出堆栈
* param [e]
* return java.lang.String
* author HuangChaobin
* createTime 2020/06/08 17:15
**/
public static String toString(Throwable e) {
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
String errorMsg = stringWriter.toString();
return errorMsg;
}
}
package com.esv.freight.notice.module.msg;
/**
* @description: 消息推送常量
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.JPushConstants
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 10:34
* @version:1.0
*/
public class MsgConstants {
public static final String PUSH_API_V3 = "https://api.jpush.cn/v3/push";
}
package com.esv.freight.notice.module.msg.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.notice.common.exception.EException;
import com.esv.freight.notice.common.response.EResponse;
import com.esv.freight.notice.module.msg.form.DevicePushForm;
import com.esv.freight.notice.module.msg.pojo.JPushResult;
import com.esv.freight.notice.module.msg.service.PushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.controller.PushController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 17:34
* @version:1.0
*/
@Slf4j
@RestController
@RequestMapping("/message")
public class PushController {
private PushService pushService;
@Autowired
public PushController(PushService pushService) {
this.pushService = pushService;
}
/**
* description 给指定设备推送消息
* param [form]
* return com.esv.freight.notice.common.response.EResponse
* author HuangChaobin
* createTime 2020/06/09 11:27
**/
@PostMapping("/push2Device")
public EResponse push2Device(@RequestBody @Validated DevicePushForm form) throws EException {
JPushResult pushResult = pushService.push2Device(form);
if (pushResult.getResult()) {
JSONObject data = new JSONObject();
data.put("msgId", pushResult.getMsgId());
return EResponse.ok(data);
} else {
return EResponse.error(pushResult.getCode(), pushResult.getMessage());
}
}
}
package com.esv.freight.notice.module.msg.dao;
import com.esv.freight.notice.module.msg.entity.NoticePushHistoryEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 消息推送记录表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-06-09 11:06:04
*/
@Mapper
public interface NoticePushHistoryDao extends BaseMapper<NoticePushHistoryEntity> {
}
package com.esv.freight.notice.module.msg.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 消息推送记录表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-06-09 11:06:04
*/
@Data
@TableName("base_notice_push_history")
public class NoticePushHistoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
* 设备类型:1-android、2-ios
*/
private Integer deviceType;
/**
* 设备ID
*/
private String registrationId;
/**
* 推送成功第三方返回的ID
*/
private String msgId;
/**
* 推送序列号
*/
private Integer sendNo;
/**
* 推送状态:-1-已推送、0-送达、1-未送达、2-registration_id 不属于该应用、3-registration_id 属于该应用,但不是该条 message 的推送目标、4-系统异常
*/
private Integer pushStatus;
/**
* 推送内容
*/
private String pushContent;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
}
package com.esv.freight.notice.module.msg.form;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.form.DevicePushForm
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 17:29
* @version:1.0
*/
@Data
public class DevicePushForm {
/**
* APP类型:1-货主、2-司机
*/
@Range(min = 1, max = 2, message = "参数appType不合法")
@NotNull(message = "参数appType不能为空")
private Integer appType;
/**
* 设备类型:1-android、2-ios
*/
@Range(min = 1, max = 2, message = "参数deviceType不合法")
@NotNull(message = "参数deviceType不能为空")
private Integer deviceType;
/**
* 帐号
*/
@Length(max = 64, message = "第三方消息推送中心注册的设备ID")
@NotEmpty(message = "参数registrationId不能为空")
private String registrationId;
/**
* Json格式的消息内容
*/
@NotNull(message = "参数message不能为空")
private JSONObject message;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.freight.notice.module.msg.pojo;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.pojo.JPushObjectInfo
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 11:13
* @version:1.0
*/
@Data
public class JPushObjectInfo {
/**
* APP类型:1-货主、2-司机
*/
private Integer appType;
/**
* 设备类型:1-android、2-ios
*/
private Integer deviceType;
/**
* 帐号
*/
private String registrationId;
/**
* Json格式的消息内容
*/
private JSONObject message;
/**
* 极光推送 appKey
**/
private String appKey;
/**
* 极光推送 appKey
**/
private String masterSecret;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.freight.notice.module.msg.pojo;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* @description: 极光推送结果Pojo
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.pojo.JPushResult
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/09 10:51
* @version:1.0
*/
@Data
public class JPushResult {
/**
* 推送结果:true-成功、false-失败
**/
private Boolean result;
/**
* 推送失败:错误码
**/
private Integer code;
/**
* 推送失败:错误信息
**/
private String message;
/**
* 推送成功序列号
**/
private Integer sendNO;
/**
* 推送成功消息ID
**/
private String msgId;
/**
* 推送内容
**/
private JSONObject pushContent;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.freight.notice.module.msg.service;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.notice.common.exception.EException;
import com.esv.freight.notice.common.response.ECode;
import com.esv.freight.notice.common.util.HttpUtils;
import com.esv.freight.notice.common.util.ThrowableUtils;
import com.esv.freight.notice.module.msg.MsgConstants;
import com.esv.freight.notice.module.msg.form.DevicePushForm;
import com.esv.freight.notice.module.msg.pojo.JPushObjectInfo;
import com.esv.freight.notice.module.msg.pojo.JPushResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.service.JPushService
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 11:07
* @version:1.0
*/
@Service("jPushService")
@RefreshScope
@Slf4j
public class JPushService {
@Value("${msg.jpush.driver.app-key}")
private String driverAppKey;
@Value("${msg.jpush.driver.master-secret}")
private String driverMasterSecret;
@Value("${msg.jpush.goodsowner.app-key}")
private String goodsOwnerAppKey;
@Value("${msg.jpush.goodsowner.master-secret}")
private String goodsOwnerMasterSecret;
/**
* description 获取推送消息
* param [form]
* return com.esv.freight.notice.module.msg.pojo.JPushObjectInfo
* author HuangChaobin
* createTime 2020/06/09 17:20
**/
public JPushObjectInfo getPushObjectInfo(DevicePushForm form) {
JPushObjectInfo jPushObjectInfo = new JPushObjectInfo();
BeanUtils.copyProperties(form, jPushObjectInfo);
if (1 == form.getAppType()) {
jPushObjectInfo.setAppKey(goodsOwnerAppKey);
jPushObjectInfo.setMasterSecret(goodsOwnerMasterSecret);
} else {
jPushObjectInfo.setAppKey(driverAppKey);
jPushObjectInfo.setMasterSecret(driverMasterSecret);
}
return jPushObjectInfo;
}
/**
* description 推送消息到指定设备
* param [jPushObjectInfo]
* return com.esv.freight.notice.module.msg.pojo.JPushResult
* author HuangChaobin
* createTime 2020/06/09 11:14
**/
public JPushResult pushMessage(JPushObjectInfo jPushObjectInfo) {
JSONObject jPushJsonObject = new JSONObject();
// 推送平台设置
if (1 == jPushObjectInfo.getDeviceType()) {
jPushJsonObject.put("platform", "android");
} else {
jPushJsonObject.put("platform", "ios");
}
// 推送设备指定
List<String> registrationIdList = new ArrayList<>(1);
registrationIdList.add(jPushObjectInfo.getRegistrationId());
JSONObject registrationIdJson = new JSONObject();
registrationIdJson.put("registration_id", registrationIdList);
jPushJsonObject.put("audience", registrationIdJson);
// 设置消息内容体
jPushJsonObject.put("message", jPushObjectInfo.getMessage());
// 推送消息
Map<String, String> headerMap = new HashMap<>(1);
headerMap.put("Authorization", this.getPushAuthorization(jPushObjectInfo.getAppType()));
String pushResult;
try {
pushResult = HttpUtils.post(MsgConstants.PUSH_API_V3, headerMap, jPushJsonObject);
} catch (Exception e) {
log.error("调用极光推送时发生错误:{}. {}", e.getMessage(), ThrowableUtils.toString(e));
throw new EException(ECode.THIRD_PARTY_ERROR.code(), "请求极光推送服务时发生错误");
}
// 判断推送结果
JSONObject pushResultJson = JSONObject.parseObject(pushResult);
JPushResult jPushResult = new JPushResult();
jPushResult.setPushContent(jPushJsonObject);
if (pushResultJson.containsKey("error")) {
// 推送失败
jPushResult.setResult(false);
jPushResult.setCode(pushResultJson.getInteger("code"));
jPushResult.setMessage(pushResultJson.getString("message"));
} else {
// 推送成功
jPushResult.setResult(true);
jPushResult.setSendNO(pushResultJson.getInteger("sendno"));
jPushResult.setMsgId(pushResultJson.getString("msg_id"));
}
return jPushResult;
}
/**
* description 获取HTTP Header(头)Authorization
* param [appType]
* return java.lang.String
* author HuangChaobin
* createTime 2020/06/08 17:27
**/
private String getPushAuthorization(Integer appType) {
String authorization;
String authInfo;
// APP类型:1-货主、2-司机
if (1 == appType) {
authInfo = goodsOwnerAppKey + ":" + goodsOwnerMasterSecret;
} else {
authInfo = driverAppKey + ":" + driverMasterSecret;
}
authorization = "Basic " + Base64.getEncoder().encodeToString(authInfo.getBytes());
return authorization;
}
}
package com.esv.freight.notice.module.msg.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.freight.notice.module.msg.entity.NoticePushHistoryEntity;
import com.esv.freight.notice.module.msg.pojo.JPushObjectInfo;
import com.esv.freight.notice.module.msg.pojo.JPushResult;
/**
* 消息推送记录表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-06-09 11:06:04
*/
public interface NoticePushHistoryService extends IService<NoticePushHistoryEntity> {
/**
* description 保存推送结果
* param [jPushObjectInfo, jPushResult]
* return java.lang.Integer
* author HuangChaobin
* createTime 2020/06/09 11:09
**/
Integer savePushResult(JPushObjectInfo jPushObjectInfo, JPushResult jPushResult);
}
package com.esv.freight.notice.module.msg.service;
import com.esv.freight.notice.module.msg.form.DevicePushForm;
import com.esv.freight.notice.module.msg.pojo.JPushResult;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.service.PushService
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 10:52
* @version:1.0
*/
public interface PushService {
/**
* description 给指定设备推送消息
* param [form]
* return com.esv.freight.notice.module.msg.pojo.JPushResult
* author HuangChaobin
* createTime 2020/06/09 10:56
**/
JPushResult push2Device(DevicePushForm form);
}
package com.esv.freight.notice.module.msg.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.freight.notice.module.msg.dao.NoticePushHistoryDao;
import com.esv.freight.notice.module.msg.entity.NoticePushHistoryEntity;
import com.esv.freight.notice.module.msg.pojo.JPushObjectInfo;
import com.esv.freight.notice.module.msg.pojo.JPushResult;
import com.esv.freight.notice.module.msg.service.NoticePushHistoryService;
import org.springframework.stereotype.Service;
@Service("noticePushHistoryService")
public class NoticePushHistoryServiceImpl extends ServiceImpl<NoticePushHistoryDao, NoticePushHistoryEntity> implements NoticePushHistoryService {
@Override
public Integer savePushResult(JPushObjectInfo jPushObjectInfo, JPushResult jPushResult) {
NoticePushHistoryEntity entity = new NoticePushHistoryEntity();
entity.setDeviceType(jPushObjectInfo.getDeviceType());
entity.setRegistrationId(jPushObjectInfo.getRegistrationId());
entity.setMsgId(jPushResult.getMsgId());
entity.setSendNo(jPushResult.getSendNO());
entity.setPushContent(jPushResult.getPushContent().toJSONString());
return this.baseMapper.insert(entity);
}
}
\ No newline at end of file
package com.esv.freight.notice.module.msg.service.impl;
import com.esv.freight.notice.common.util.ThrowableUtils;
import com.esv.freight.notice.module.msg.form.DevicePushForm;
import com.esv.freight.notice.module.msg.pojo.JPushObjectInfo;
import com.esv.freight.notice.module.msg.pojo.JPushResult;
import com.esv.freight.notice.module.msg.service.JPushService;
import com.esv.freight.notice.module.msg.service.NoticePushHistoryService;
import com.esv.freight.notice.module.msg.service.PushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.service.impl.PushServiceImpl
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/08 10:53
* @version:1.0
*/
@Service("pushService")
@Slf4j
public class PushServiceImpl implements PushService {
private JPushService jPushService;
private NoticePushHistoryService noticePushHistoryService;
@Autowired
public PushServiceImpl(JPushService jPushService, NoticePushHistoryService noticePushHistoryService) {
this.jPushService = jPushService;
this.noticePushHistoryService = noticePushHistoryService;
}
@Override
public JPushResult push2Device(DevicePushForm form) {
// 1:获取推送目标信息
JPushObjectInfo jPushObjectInfo = jPushService.getPushObjectInfo(form);
// 2:推送消息
JPushResult jPushResult = jPushService.pushMessage(jPushObjectInfo);
// 3:推送成功,保存记录
if (jPushResult.getResult()) {
try {
noticePushHistoryService.savePushResult(jPushObjectInfo, jPushResult);
} catch (Exception e) {
log.error("消息推送成功,保存消息记录失败:{}. {}", e.getMessage(), ThrowableUtils.toString(e));
}
}
return jPushResult;
}
}
package com.esv.freight.notice.module.sms.form; package com.esv.freight.notice.module.sms.form;
import lombok.Data; import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
...@@ -28,4 +30,9 @@ public class CaptchaForm { ...@@ -28,4 +30,9 @@ public class CaptchaForm {
@Length(min = 6, max = 6, message = "参数captcha长度不合法") @Length(min = 6, max = 6, message = "参数captcha长度不合法")
private String captcha; private String captcha;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
} }
...@@ -58,4 +58,13 @@ sms: ...@@ -58,4 +58,13 @@ sms:
captcha: captcha:
frequency: 60 frequency: 60
total: 5 total: 5
period: 10 period: 10
\ No newline at end of file #消息
msg:
jpush:
driver:
app-key: 78da92de9f4b747d4778926a
master-secret: ac02a8a517d0eda6b187521c
goodsowner:
app-key: 6b42f23df17f4e4e4f2bfda8
master-secret: c6e32e82c951e93b861a1667
\ No newline at end of file
...@@ -58,4 +58,13 @@ sms: ...@@ -58,4 +58,13 @@ sms:
captcha: captcha:
frequency: 60 frequency: 60
total: 20 total: 20
period: 10 period: 10
\ No newline at end of file #消息
msg:
jpush:
driver:
app-key: 78da92de9f4b747d4778926a
master-secret: ac02a8a517d0eda6b187521c
goodsowner:
app-key: 6b42f23df17f4e4e4f2bfda8
master-secret: c6e32e82c951e93b861a1667
\ No newline at end of file
...@@ -3,9 +3,9 @@ server: ...@@ -3,9 +3,9 @@ server:
servlet: servlet:
context-path: /notice context-path: /notice
nacos: nacos:
url: localhost:8848 url: 192.168.31.248:8848
namespace: 548b506d-8d19-4d54-9715-bb0ac3a655b2 namespace: aad5aa26-5351-4e7a-a65e-ecb332f3c52c
group: FREIGHT_GROUP group: DEFAULT_GROUP
spring: spring:
application: application:
name: freight-notice-service name: freight-notice-service
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.esv.freight.notice.module.msg.dao.NoticePushHistoryDao">
<!-- 可根据自己的需求,是否要使用 -->
<resultMap type="com.esv.freight.notice.module.msg.entity.NoticePushHistoryEntity" id="noticePushHistoryMap">
<result property="id" column="id"/>
<result property="deviceType" column="device_type"/>
<result property="registrationId" column="registration_id"/>
<result property="msgId" column="msg_id"/>
<result property="sendNo" column="send_no"/>
<result property="pushStatus" column="push_status"/>
<result property="pushContent" column="push_content"/>
<result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/>
</resultMap>
</mapper>
\ No newline at end of file
package com.esv.freight.notice.module.msg.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.notice.BaseTestController;
import com.esv.freight.notice.common.response.ECode;
import com.esv.freight.notice.module.msg.form.DevicePushForm;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.transaction.annotation.Transactional;
/**
* @description:
* @project: freight-notice-service
* @name: com.esv.freight.notice.module.msg.controller.PushControllerTest
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/09 11:27
* @version:1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Transactional
@Rollback(false)
public class PushControllerTest extends BaseTestController {
/**
* 给指定设备推送消息
**/
@Test
public void a1_push2Device_success_test() throws Exception {
String url = "/message/push2Device";
// 构造数据
DevicePushForm form = new DevicePushForm();
form.setAppType(1); // APP类型:1-货主、2-司机
form.setDeviceType(1); // 设备类型:1-android、2-ios
form.setRegistrationId("18071adc038dfcf8ab0");
// 设置自定义消息[message]
JSONObject message = new JSONObject();
message.put("msg_content", "这是一条测试消息-" + System.currentTimeMillis());
message.put("title", "测试消息标题-" + System.currentTimeMillis());
message.put("content_type", "text");
JSONObject extras = new JSONObject();
extras.put("messageType", 0);
extras.put("data", new JSONObject());
message.put("extras", extras);
form.setMessage(message);
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(form.toString()))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String responseStr = mvcResult.getResponse().getContentAsString();
log.info(responseStr);
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertEquals(ECode.SUCCESS.code(), result.getIntValue("code"));
Assert.assertTrue(result.getJSONObject("data").containsKey("msgId"));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment