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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值