@Aspect KafkaSendHandle

@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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章