@Aspect
@Component
public class KafkaSendHandle {
private static Logger log = LoggerFactory.getLogger(KafkaSendHandle.class);
@Autowired
private ObjectMapper objectMapper;
@Autowired
private KafkaTemplate kafkaTemplate;
@Around("@annotation(com.yunkai.component.kafka.aop.KafkaSend)")
public Object handle(ProceedingJoinPoint point) throws Throwable {
//获取需要的参数属性
Object[] args = point.getArgs();
Method me = ((MethodSignature) point.getSignature()).getMethod();
//获取所有方法名
Signature signature = point.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
String[] allParameterNames = methodSignature.getParameterNames();
KafkaSend annotation = me.getAnnotation(KafkaSend.class);
String topic = annotation.topic();
int key = annotation.key();
OrderEnum orderEnum = annotation.order();
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < args.length; i++) {
map.put(allParameterNames[i], args[i]);
}
String value = objectMapper.writeValueAsString(map);
Object result;
ListenableFuture<SendResult<Integer, String>> sendResult;
// 先执行方法
if (OrderEnum.AFTER.equals(orderEnum)) {
result = point.proceed(args);
log.info("方法执行完毕,time is {}", System.currentTimeMillis());
sendResult = kafkaTemplate.send(topic, value);
} else {
sendResult = kafkaTemplate.send(topic, value);
result = point.proceed(args);
log.info("方法执行完毕,time is {}", System.currentTimeMillis());
}
sendResult.addCallback(new KafkaSuccess(), new KafkaFail());
log.info("kafka send success,topic:{},key:{},value:{}", topic, key, value);
return result;
}
}