本篇文章以实际生产过程中处理极光推送消息后落地消息到数据库为例!
1.自定义需要推送后保存消息的注解
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Message {
/**
* 是否需要保存消息日志,缺省为需要
* @return
*/
boolean saveMessage() default true;
}
2.实现消息切面
import com.ouyeel.ssx.common.annotation.Message;
import com.ouyeel.ssx.common.dto.MessageParam;
import com.ouyeel.ssx.common.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Aspect
@Component
public class MessageAspect {
@Autowired
private MessageService messageService;
@Pointcut("@annotation(com.ouyeel.ssx.common.annotation.Message)")
public void pointcut() {
// do nothing
}
//保存推送消息日志
@Around("pointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
Message messageAnnotation = method.getAnnotation(Message.class);
Object result = point.proceed();
if(messageAnnotation.saveMessage()){
int success = 0;
if(1 == (int) result){
success = 1;
}
try {
if(point.getArgs() != null && point.getArgs().length > 0){
for (Object o : point.getArgs()) {
if(o != null && o instanceof MessageParam){
MessageParam m = (MessageParam)o;
m.setIsSuccess(success);
messageService.saveBatchMessage(m);
log.info("====【记录保存Message消息成功】result:success");
}
}
}
}catch (Exception e){
log.error("=====【记录保存Message消息失败】error:{}",e.getMessage());
}
}
return result;
}
}
3.极光推送消息方法上增加自定义的消息注解
@Message
@Override
public int jpush(JPushCommonParam param) throws APIConnectionException, APIRequestException {
try {
xxx
return 1;
}catch(Exception e){
log.info("=======【推送失败】sendPush exception: "+e.getMessage());
}
return 0;
}