具有AOP的动态卡夫卡消费者

时间:2018-06-25 16:44:30

标签: java apache-kafka aop spring-aop spring-kafka

我很少有动态的Kafka使用者(基于部门ID等。),您可以在下面找到代码。

基本上,我想记录每个onMessage()方法调用所花费的时间,因此我创建了@LogExecutionTime方法级别的自定义注释并将其添加到onMessage()方法中。 但是,即使有关于该主题的消息出现,并且其他一切正常,即使我的logExecutionTime()被调用,我的LogExecutionTimeAspect中的onMessage()也从未被调用。

请帮助我解决LogExecutionTimeAspect类,以便它开始工作吗?

LogExecutionTime:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}

LogExecutionTimeAspect类:

@Aspect
@Component
public class LogExecutionTimeAspect {
    @Around("within(com.myproject..*) && @annotation(LogExecutionTime)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object object = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        System.out.println(" Time taken by Listener ::"+(endTime-startTime)+"ms");
        return object;
    }
}

DepartmentsMessageConsumer类:

@Component
public class DepartmentsMessageConsumer implements MessageListener  {

    @Value(value = "${spring.kafka.bootstrap-servers}" )
    private String bootstrapAddress;

    @PostConstruct
    public void init() {
        Map<String, Object> consumerProperties = new HashMap<>();
        consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, 
                                     bootstrapAddress);
        consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "DEPT_ID_HERE");
        ContainerProperties containerProperties = 
            new ContainerProperties("com.myproj.depts.topic");
        containerProperties.setMessageListener(this);
        DefaultKafkaConsumerFactory<String, Greeting> consumerFactory =
                new DefaultKafkaConsumerFactory<>(consumerProperties, 
                    new StringDeserializer(), 
                    new JsonDeserializer<>(Department.class));
        ConcurrentMessageListenerContainer container =
                new ConcurrentMessageListenerContainer<>(consumerFactory, 
                            containerProperties);
        container.start();
    }

    @Override
    @LogExecutionTime
    public void onMessage(Object message) {
        ConsumerRecord record = (ConsumerRecord) message;
        Department department = (Department)record.value();
        System.out.println(" department :: "+department);
    }
}

ApplicationLauncher类:

@SpringBootApplication
@EnableKafka
@EnableAspectJAutoProxy
@ComponentScan(basePackages = { "com.myproject" })
public class ApplicationLauncher extends SpringBootServletInitializer { 
    public static void main(String[] args) {
        SpringApplication.run(ApplicationLauncher.class, args);
    }
}

编辑:

我尝试过@EnableAspectJAutoProxy(exposeProxy=true),但是没有用。

1 个答案:

答案 0 :(得分:1)

您应该考虑在@EnableAspectJAutoProxy上启用此选项:

/**
 * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
 * for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
 * Off by default, i.e. no guarantees that {@code AopContext} access will work.
 * @since 4.3.1
 */
boolean exposeProxy() default false;

另一方面,有这样的东西,它将比AOP更好:

/**
 * A plugin interface that allows you to intercept (and possibly mutate) records received by the consumer. A primary use-case
 * is for third-party components to hook into the consumer applications for custom monitoring, logging, etc.
 *
 * <p>
 * This class will get consumer config properties via <code>configure()</code> method, including clientId assigned
 * by KafkaConsumer if not specified in the consumer config. The interceptor implementation needs to be aware that it will be
 * sharing consumer config namespace with other interceptors and serializers, and ensure that there are no conflicts.
 * <p>
 * Exceptions thrown by ConsumerInterceptor methods will be caught, logged, but not propagated further. As a result, if
 * the user configures the interceptor with the wrong key and value type parameters, the consumer will not throw an exception,
 * just log the errors.
 * <p>
 * ConsumerInterceptor callbacks are called from the same thread that invokes {@link org.apache.kafka.clients.consumer.KafkaConsumer#poll(long)}.
 * <p>
 * Implement {@link org.apache.kafka.common.ClusterResourceListener} to receive cluster metadata once it's available. Please see the class documentation for ClusterResourceListener for more information.
 */
public interface ConsumerInterceptor<K, V> extends Configurable {

更新

  

@EnableAspectJAutoProxy(exposeProxy=true)不起作用,我知道我可以使用拦截器,但是我想使其与AOP一起使用。

然后,我建议您考虑将DepartmentsMessageConsumerConcurrentMessageListenerContainer分开。我的意思是将ConcurrentMessageListenerContainer移到单独的@Configuration类中。 ApplicationLauncher是很好的候选人。将其设置为@Bean,并取决于您的DepartmentsMessageConsumer进行注入。关键是,您需要给AOP一个机会来DepartmentsMessageConsumer进行工具测试,但是使用@PostConstruct时,要实例化并从Kafka开始消费还为时过早。