[英]Dynamic Kafka Consumer with AOP
我有幾個動態的Kafka使用者(基於部門ID等),您可以在下面找到代碼。
基本上,我想記錄每個onMessage()
方法調用花費的時間,因此我創建了@LogExecutionTime
方法級別的自定義注釋,並將其添加到onMessage()
方法中。 但是,即使每當有關於主題的消息被調用時,我的onMessage()
都會被調用,而我的logExecutionTime()
LogExecutionTimeAspect
永遠不會被調用,並且其他一切都很好。
您能幫我缺少什么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)
,但是沒有用。
您應該考慮在@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 {
UPDATE
@EnableAspectJAutoProxy(exposeProxy=true)
不起作用,我知道我可以使用攔截器,但我想使其與AOP一起使用。
然后,我建議您考慮將DepartmentsMessageConsumer
和ConcurrentMessageListenerContainer
分開。 我的意思是將ConcurrentMessageListenerContainer
移到單獨的@Configuration
類中。 ApplicationLauncher
是一個很好的候選人。 將其設置為@Bean
並依賴於DepartmentsMessageConsumer
進行注入。 關鍵是您需要給AOP一個機會來測試DepartmentsMessageConsumer
,但是使用@PostConstruct
,現在實例化並從Kafka開始使用還為時過早。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.