我有一个AOP方面来计算一些服务被调用的次数:
@Aspect
@Component
public class CounterAspect {
private Map<Integer, Integer> gettingEventStatistics = new HashMap<>();
@Pointcut("execution(Event EventService+.getById(Integer))")
private void gettingEvent() {}
@AfterReturning(pointcut = "gettingEvent()", returning = "retVal")
public void countGettingEvent(JoinPoint joinPoint, Object retVal) {
Integer id = (Integer) joinPoint.getArgs()[0];
if (id != null && retVal != null) {
Integer currentCounterValue = gettingEventStatistics.get(id);
gettingEventStatistics.put(id, currentCounterValue == null ? 1 : currentCounterValue + 1);
}
}
}
如何使用Hibernate在DB中存储这样的信息?
答案 0 :(得分:1)
我已经制作了以下解决方案 - 为统计数据创建实体
@Entity
public class GettingEventsStats {
@Id
private Integer eventId;
private Integer gettingCounter;
//getters, setters, etc.
在我的方面注入了DAO委托这样的功能:
@Repository
public class HibernateStatsDao implements StatsDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public GettingEventsStats getGettingEventStats(Integer eventId) {
return sessionFactory.getCurrentSession().get(GettingEventsStats.class, eventId);
}
@Override
public void createGettingEventCounter(Integer eventId) {
GettingEventsStats gettingEventsStats = new GettingEventsStats();
gettingEventsStats.setEventId(eventId);
gettingEventsStats.setGettingCounter(1);
sessionFactory.getCurrentSession().save(gettingEventsStats);
}
@Override
public void updateGettingEventCounter(Integer eventId) {
GettingEventsStats gettingEventStats = getGettingEventStats(eventId);
gettingEventStats.setGettingCounter(gettingEventStats.getGettingCounter() + 1);
sessionFactory.getCurrentSession().update(gettingEventStats);
}
}
并将方面逻辑更改为:
@Autowired
private StatsDao statsDao;
@Pointcut("execution(Event EventService+.getById(Integer))")
private void gettingEvent() {}
@AfterReturning(pointcut = "gettingEvent()", returning = "retVal")
public void countGettingEvent(JoinPoint joinPoint, Object retVal) {
Integer eventId = (Integer) joinPoint.getArgs()[0];
if (eventId != null && retVal != null) {
GettingEventsStats gettingEventStats = statsDao.getGettingEventStats(eventId);
if (gettingEventStats == null) {
statsDao.createGettingEventCounter(eventId);
} else {
statsDao.updateGettingEventCounter(eventId);
}
}
}
答案 1 :(得分:0)
最简单的方法是将其解析为JSON并存储为字符串。请记住,增加列最大内存大小。
答案 2 :(得分:0)
您将使用此方法保存大量条目。更好地使用D ropwizard Metrics,它使用Reservoirs进行数据采样和自定义报告。
通常,通过JMX向APM工具公开指标会更好。或者您应该使用Graphite或Graphana来实现此目的。