spring-boot-starter-aop
创建了一个方面,该方面在调用我的服务方法之后执行。
方面:
@Slf4j
@Aspect
@Configuration
public class ContactAmountAspect {
@Autowired
ContactRepository contactRepository;
@Autowired
MeterRegistry registry;
@AfterReturning(value = "execution(* mypackage.ContactService.*(..))")
public void monitorContactAmount() {
Gauge
.builder("contacts.amount", contactRepository.findAll(), List::size)
.register(registry);
log.info("Amount of contacts in database: {}", contactRepository.findAll().size());
}
}
在/prometheus
端点上,我只看到应用程序启动后第一次调用时的联系人数量。
如果现在我呼叫POST休息端点并向我的数据库中添加联系人,则只有log.info
会打印出新的联系人数量,但我的仪表却无济于事。
顺序:
1. App Startup (let's say with 1 contact in DB)
2. Call Rest Endpoint "getAllContacts"
3. My AOP method starts
4. The gauge monitors contact amount of 1
5. the logger logs contact amount of 1
6. Call Rest Endpoint "postOneContact"
7. My AOP method starts
8. The gauge does nothing or monitors still the amount of 1
9. the logger logs contact amount of 2
我在做什么错了?
或者还有另一种方法可以监视数据库表中的记录数量?
答案 0 :(得分:0)
我发现量规制造器不起作用。
相反,我必须使用此:
@Slf4j
@Aspect
@Configuration
public class AspectConfig {
@Autowired
ContactRepository contactRepository;
AtomicInteger amount = new AtomicInteger(0);
@AfterReturning("execution(* mypackage.ContactService.*(..))")
public void monitorContactAmount() {
Metrics.gauge("database.contacts.amount", amount);
amount.set(contactRepository.findAll().size());
log.info("Monitoring amount of contacts in database: {}", contactRepository.findAll().size());
}
}
答案 1 :(得分:0)
实际上,问题在于量规的初始化不正确。您应该这样声明该指标:
Gauge .builder("contacts.amount", contactRepository, ContactRepository::count) .register(registry);
此代码对我有用!