2015-10-13 143 views
0

我試圖使用AOP和statsd的組合來測量我的代碼中的度量。特別是,我希望開發人員能夠只需添加註釋的方法,並指定其名稱和標籤,如下創建一個定時器:將變量傳遞給某個方面

@Timed(name="executeHistoryDataSet", tags={dataSetInfo.getLabel()}) 
@Override 
public String executeHistoryDataSet(DataSet dataSetInfo) throws DataServiceException { 
    String results = executeDataSet(dataSetInfo); 
    return results; 
} 

這將包括有關參數的標籤信息。但是,這顯示一個attribute value must be constant錯誤,因爲註釋的參數不能是可變的,其中dataSetInfo.getLabel()肯定不是。

開發人員可以在不創建新的方面和建議的情況下創建新的定時器(@Timed可能是所有定時器的註釋),所以有什麼方法可以實現此功能,通過類似tags的建議,但這可能不是恆定的,並且從方法到方法有所不同?


這裏是註釋本身:

public @interface Timed { 
    String name(); 
    String[] tags(); 
} 

而其方面:

@Aspect 
public class MetricsAspects { 

    private static final StatsDClient statsd = new NonBlockingStatsDClient(
     "my.prefix",     //prefix to any stats 
     "statsd-host",     //often "localhost" 
     8125,       //port 
     "tag", "another tag"   //tags always applied to stats 
    ); 

    @Around ("execution(* *(..) && @annotation(timed)") 
    public Object timeAround(ProceedingJoinPoint point, Timed timed) throws Throwable { 

     String metricName = timed.name(); 
     String[] metricTags = timed.tags(); 
     long start = System.currentTimeMillis(); 
     Object result = point.proceed(); 
     long duration = System.currentTimeMillis() - start; 
     statsd.recordExecutionTime(metricName, duration, metricTags); 
     return result; 
    } 
} 
+0

該錯誤有點誤導。註釋成員值需要是常量表達式,類文字或枚舉常量。 –

回答

0

一個註釋需要將其參數在編譯時已知。由於在編譯時不知道哪個對象被賦予了這個函數,只要它被執行,編譯器就會拋出錯誤。