springboot自定義jmx對象


在使用springboot-admin對springboot項目進行監控的時候我們發現其是具有web訪問jmx對象的功能的,那它內部是怎么實現的呢。

Jolokia是一個JMX-http橋梁,它提供了訪問JMX bean的HTTP訪問方式。

<dependency>
    <groupId>org.jolokia</groupId>
    <artifactId>jolokia-core</artifactId>
</dependency>

 

什么情況我們需要使用JMX? 我認為比較實用有如下2點:

1、獲取java對象里的屬性的實時情況。

2、動態修改對象里的屬性的值。

 

例如:你有一個耗時較長的定時任務,里面會處理一批數據,這時通過jmx暴露當前已處理的數據的相關數據就能得到實時的結果(當然,你可以通過寫日志、數據庫、緩存來實現,但這無疑增加了更業務無關的代碼)。

 

那要怎么做呢?

首先看一下相關注解定義

將類的所有實例標識為JMX受控資源 ManagedResource @ManagedResource Class 類
將方法標識為JMX操作 ManagedOperation @ManagedOperation  Method方法
將getter或者setter標識為部分JMX屬性 ManagedAttribute @ManagedAttribute Method (only getters and setters) 方法(僅getters和setters)
定義操作參數說明 ManagedOperationParameter @ManagedOperationParameter@ManagedOperationParameters Method 方法

例子:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedResource;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@ManagedResource (objectName= "com.longge:name=spideMpbServiceImpl" , description= "brower spider service" )
public class SpideMpbServiceImpl implements SpideMpbService {
    // 臨時表當前最大id
    private Long tempMaxId = 0L;
     
    /**
     * 暴露mbean方法
     * @return
     */
    @ManagedAttribute(description="temp info now max id")
    public Long getNowTempMaxId() {
        return tempMaxId;
    }
}

 在JMC的Mbean選項卡、springboot-admin的jmx就能看到這屬性和這方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM