下面列出了怎么用org.springframework.boot.actuate.endpoint.annotation.ReadOperation的API类实例代码及写法,或者点击链接到github查看源代码。
@ReadOperation
public List<Map<String, String>> getAll() {
List<Map<String, String>> result = new ArrayList<>();
for (Entry<String, WebSocketRoutedSession> entry : webSocketProxyServerHandler.getRoutedSessions().entrySet()) {
WebSocketRoutedSession currentSession = entry.getValue();
Map<String, String> map = new LinkedHashMap<>();
map.put("sessionId", entry.getKey());
map.put("clientAddress", currentSession.getServerRemoteAddress());
map.put("gatewayPath", currentSession.getServerUri());
map.put("serviceUrl", currentSession.getClientUri());
map.put("serviceSessionId", currentSession.getClientId());
result.add(map);
}
return result;
}
@ReadOperation
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<>(8);
if (!(ClassUtils.isAssignable(applicationContext.getEnvironment().getClass(),
ConfigurableEnvironment.class))) {
result.put("error", "environment type not match ConfigurableEnvironment: "
+ applicationContext.getEnvironment().getClass().getName());
}
else {
result.put("nacosConfigMetadata", nacosConfigMetadataMap.values());
result.put("nacosConfigGlobalProperties",
PropertiesUtils.extractSafeProperties(applicationContext.getBean(
CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class)));
}
return result;
}
/**
* @return nacos discovery endpoint
*/
@ReadOperation
public Map<String, Object> nacosDiscovery() {
Map<String, Object> result = new HashMap<>();
result.put("NacosDiscoveryProperties", nacosDiscoveryProperties);
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
List<ServiceInfo> subscribe = Collections.emptyList();
try {
subscribe = namingService.getSubscribeServices();
}
catch (Exception e) {
log.error("get subscribe services from nacos fail,", e);
}
result.put("subscribe", subscribe);
return result;
}
@ReadOperation
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<>(16);
result.put("NacosConfigProperties", properties);
List<NacosPropertySource> all = NacosPropertySourceRepository.getAll();
List<Map<String, Object>> sources = new ArrayList<>();
for (NacosPropertySource ps : all) {
Map<String, Object> source = new HashMap<>(16);
source.put("dataId", ps.getDataId());
source.put("lastSynced", dateFormat.get().format(ps.getTimestamp()));
sources.add(source);
}
result.put("Sources", sources);
result.put("RefreshHistory", refreshHistory.getRecords());
return result;
}
@ReadOperation
public Map<String, Properties> readProperties() {
Map<String, Properties> reports = new HashMap<>();
connector.getSessions().forEach(sessionId -> {
try {
Properties p = new Properties();
p.putAll(sessionSettings.getDefaultProperties());
p.putAll(sessionSettings.getSessionProperties(sessionId));
p.putAll(addSessionIdProperties(sessionId));
reports.put(sessionId.toString(), p);
} catch (ConfigError e) {
throw new IllegalStateException(e);
}
});
return reports;
}
@Autowired
EndpointCommand(ApplicationContext appCtx) {
appCtx.getBeansWithAnnotation(Endpoint.class).entrySet().stream()
.sorted(Comparator.comparing(e -> e.getKey()))
.forEachOrdered(entry -> {
log.debug("{} : {}", entry.getKey(), entry.getValue().getClass().getName());
for (Method m : entry.getValue().getClass().getDeclaredMethods()) {
if (m.isAnnotationPresent(ReadOperation.class) || m.isAnnotationPresent(WriteOperation.class)) {
log.debug("\tOp: {}", m.getName());
for (Parameter p : m.getParameters()) {
log.debug("\t\tParameter {}, {}", p.getName(), p.getType().getName());
}
}
}
});
}
/**
* GET /management/jhi-metrics
* <p>
* Give metrics displayed on Metrics page
*
* @return a Map with a String defining a category of metrics as Key and
* another Map containing metrics related to this category as Value
*/
@ReadOperation
public Map<String, Map> allMetrics() {
Map<String, Map> results = new HashMap<>();
// JVM stats
results.put("jvm", this.jvmMemoryMetrics());
// HTTP requests stats
results.put("http.server.requests", this.httpRequestsMetrics());
// Cache stats
results.put("cache", this.cacheMetrics());
// Service stats
results.put("services", this.serviceMetrics());
// Database stats
results.put("databases", this.databaseMetrics());
// Garbage collector
results.put("garbageCollector", this.garbageCollectorMetrics());
// Process stats
results.put("processMetrics", this.processMetrics());
return results;
}
@ReadOperation
public ConsulData invoke() {
ConsulData data = new ConsulData();
// data.setKeyValues(kvClient.getKeyValueRecurse());
Response<Map<String, Service>> agentServices = this.consul.getAgentServices();
data.setAgentServices(agentServices.getValue());
Response<Map<String, List<String>>> catalogServices = this.consul
.getCatalogServices(CatalogServicesRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
for (String serviceId : catalogServices.getValue().keySet()) {
Response<List<CatalogService>> response = this.consul
.getCatalogService(serviceId, CatalogServiceRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
data.getCatalogServices().put(serviceId, response.getValue());
}
Response<List<Node>> catalogNodes = this.consul
.getCatalogNodes(CatalogNodesRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
data.setCatalogNodes(catalogNodes.getValue());
return data;
}
@ReadOperation
public HaloMetricResponse HaloMetric() {
HaloMetricResponse haloMetricResponse=new HaloMetricResponse();
MetricResponse jvmThreadsLive=metric("jvm.threads.live",null);
haloMetricResponse.setJvmThreadslive(String.valueOf(jvmThreadsLive.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedHeap=metric("jvm.memory.used", Arrays.asList("area:heap") );
haloMetricResponse.setJvmMemoryUsedHeap(String.valueOf(jvmNemoryUsedHeap.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedNonHeap=metric("jvm.memory.used", Arrays.asList("area:nonheap") );
haloMetricResponse.setJvmMemoryUsedNonHeap(String.valueOf(jvmNemoryUsedNonHeap.getMeasurements().get(0).getValue()));
// 2.0 actuator/metrics 中没有这个key
MetricResponse systemLoadAverage=metric("system.load.average.1m", null );
if(systemLoadAverage!=null){
haloMetricResponse.setSystemloadAverage(String.valueOf(systemLoadAverage.getMeasurements().get(0).getValue()));
}
MetricResponse heapCommitted=metric("jvm.memory.committed", Arrays.asList("area:heap") );
haloMetricResponse.setHeapCommitted(String.valueOf(heapCommitted.getMeasurements().get(0).getValue()));
MetricResponse nonheapCommitted=metric("jvm.memory.committed", Arrays.asList("area:nonheap") );
haloMetricResponse.setNonheapCommitted(String.valueOf(nonheapCommitted.getMeasurements().get(0).getValue()));
MetricResponse heapMax=metric("jvm.memory.max", Arrays.asList("area:heap") );
haloMetricResponse.setHeapMax(String.valueOf(heapMax.getMeasurements().get(0).getValue()));
getGcinfo(haloMetricResponse);
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getHeapMemoryUsage();
haloMetricResponse.setHeapInit(String.valueOf(memoryUsage.getInit()));
Runtime runtime = Runtime.getRuntime();
haloMetricResponse.setProcessors(String.valueOf(runtime.availableProcessors()));
return haloMetricResponse;
}
@ReadOperation
public Map recordOverLoad() {
Map map = new HashMap();
map.put("name", "ppppp");
System.err.println("00000ppppppppppppppppp");
return map;
}
/**
* Returns a reversed Output from the Logfile.
*
* @return
* @throws IOException
*/
@ReadOperation
public List<String> getLog() throws IOException {
Resource logFileResource = getLogFileResource();
if (logFileResource == null || !logFileResource.isReadable()) {
return null;
}
ReversedLinesFileReader reversedLinesFileReader = new ReversedLinesFileReader(logFileResource.getFile(), StandardCharsets.UTF_8);
List<String> log = new ArrayList<>();
for (int i = 0; i < 20; i++) {
final String line = reversedLinesFileReader.readLine();
if (line.startsWith("\t") || line.isEmpty()) { //Remove Stacktrace and Empty lines
i--;
continue;
}
log.add(line);
}
reversedLinesFileReader.close();
return log;
}
@SuppressWarnings("unused")
@ReadOperation
public Mono<Map<String, Object>> reportServerTime() {
return getNtpTimeOffset()
.map(timeOffset -> {
Map<String, Object> rsp = new LinkedHashMap<>();
rsp.put("serverTime", Instant.now().toString());
rsp.put("ntpOffsetMillis", timeOffset);
return rsp;
});
}
@ReadOperation
public Map<String, String> hello() {
Map<String, String> result = new HashMap<>();
result.put("author", "Luis");
result.put("age", "25");
result.put("email", "[email protected]");
return result;
}
@ReadOperation
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<String, Object>();
result.put("version", this.getClass().getPackage().getImplementationVersion());
result.put("properties", arthasProperties);
result.put("agents", tunnelServer.getAgentInfoMap());
result.put("clientConnections", tunnelServer.getClientConnectionInfoMap());
return result;
}
@ReadOperation
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<String, Object>();
if (arthasConfigMap != null) {
result.put("arthasConfigMap", arthasConfigMap);
}
String errorMessage = arthasAgent.getErrorMessage();
if (errorMessage != null) {
result.put("errorMessage", errorMessage);
}
return result;
}
@ReadOperation
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<>(8);
result.put("nacosDiscoveryGlobalProperties",
PropertiesUtils.extractSafeProperties(applicationContext.getBean(
DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class)));
NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory
.getSingleton();
JSONArray array = new JSONArray();
for (NamingService namingService : nacosServiceFactory.getNamingServices()) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("servicesOfServer",
namingService.getServicesOfServer(0, PAGE_SIZE));
jsonObject.put("subscribeServices", namingService.getSubscribeServices());
array.add(jsonObject);
}
catch (Exception e) {
jsonObject.put("serverStatus", namingService.getServerStatus() + ": "
+ NacosUtils.SEPARATOR + e.getMessage());
}
}
result.put("namingServersStatus", array);
return result;
}
@ReadOperation
public Map<String, Object> invoke() {
final Map<String, Object> result = new HashMap<>();
if (sentinelProperties.isEnabled()) {
result.put("appName", AppNameUtil.getAppName());
result.put("logDir", LogBase.getLogBaseDir());
result.put("logUsePid", LogBase.isLogNameUsePid());
result.put("blockPage", SentinelConfig.getConfig(BLOCK_PAGE_URL_CONF_KEY));
result.put("metricsFileSize", SentinelConfig.singleMetricFileSize());
result.put("metricsFileCharset", SentinelConfig.charset());
result.put("totalMetricsFileCount", SentinelConfig.totalMetricFileCount());
result.put("consoleServer", TransportConfig.getConsoleServerList());
result.put("clientIp", TransportConfig.getHeartbeatClientIp());
result.put("heartbeatIntervalMs", TransportConfig.getHeartbeatIntervalMs());
result.put("clientPort", TransportConfig.getPort());
result.put("coldFactor", sentinelProperties.getFlow().getColdFactor());
result.put("filter", sentinelProperties.getFilter());
result.put("datasource", sentinelProperties.getDatasource());
final Map<String, Object> rules = new HashMap<>();
result.put("rules", rules);
rules.put("flowRules", FlowRuleManager.getRules());
rules.put("degradeRules", DegradeRuleManager.getRules());
rules.put("systemRules", SystemRuleManager.getRules());
rules.put("authorityRule", AuthorityRuleManager.getRules());
rules.put("paramFlowRule", ParamFlowRuleManager.getRules());
}
return result;
}
@ReadOperation
public Status getStatus() {
Status status = new Status();
status.email.enabled = !emailProperties.isDisabled();
status.email.working = EmailConfiguration.isEmailSet();
status.firebase.enabled = firebaseService.isEnabled();
status.firebase.initialized = firebaseService.isInitialized();
status.firebase.proceedable = firebaseService.canProceed();
status.pepperSet = SecurePropertyConfig.isPepperSet();
return status;
}
@ReadOperation
public List<LoggedUser> getLoggedInUsers() {
return authService.getUsersFromSessionRegistry()
.stream()
.map(customUser -> modelMapper.map(customUser, LoggedUser.class))
.collect(Collectors.toList());
}
@ReadOperation
public Map<String, Object> bucket4jConfig() {
Map<String, Object> result = new HashMap<>();
if(servletConfigs != null) {
result.put("servlet", servletConfigs.getFilterConfiguration());
}
if(zuulConfigs != null) {
result.put("zuul", zuulConfigs.getFilterConfiguration());
}
if(webfluxConfigs != null) {
result.put("webflux", webfluxConfigs.getFilterConfiguration());
}
return result;
}
@ReadOperation
public MarathonData info() {
try {
return MarathonData.builder()
.serverInfo(marathon.getServerInfo())
.apps(marathon.getApps().getApps())
.build();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return MarathonData.builder().build();
}
@ReadOperation
public String kafkaStreamsTopology() {
final List<StreamsBuilderFactoryBean> streamsBuilderFactoryBeans = this.kafkaStreamsRegistry.streamsBuilderFactoryBeans();
final StringBuilder topologyDescription = new StringBuilder();
streamsBuilderFactoryBeans.stream()
.forEach(streamsBuilderFactoryBean ->
topologyDescription.append(streamsBuilderFactoryBean.getTopology().describe().toString()));
return topologyDescription.toString();
}
@ReadOperation
public String kafkaStreamsTopology(@Selector String applicationId) {
if (!StringUtils.isEmpty(applicationId)) {
final StreamsBuilderFactoryBean streamsBuilderFactoryBean = this.kafkaStreamsRegistry.streamsBuilderFactoryBean(applicationId);
if (streamsBuilderFactoryBean != null) {
return streamsBuilderFactoryBean.getTopology().describe().toString();
}
else {
return NO_TOPOLOGY_FOUND_MSG;
}
}
return NO_TOPOLOGY_FOUND_MSG;
}
@ReadOperation
@Nullable
public CircuitBreakerView circuitBreaker(@Selector final String name) {
final CircuitBreaker breaker = breakers.get(name);
if (breaker == null) {
return null;
}
return toView(breaker);
}
@ReadOperation
public CircuitBreakerEventsEndpointResponse getAllCircuitBreakerEvents() {
return new CircuitBreakerEventsEndpointResponse(eventConsumerRegistry.getAllEventConsumer()
.flatMap(CircularEventConsumer::getBufferedEvents)
.sorted(Comparator.comparing(CircuitBreakerEvent::getCreationTime))
.map(CircuitBreakerEventDTOFactory::createCircuitBreakerEventDTO).toJavaList());
}
@ReadOperation
public CircuitBreakerEventsEndpointResponse getEventsFilteredByCircuitBreakerNameAndEventType(
@Selector String name, @Selector String eventType) {
return new CircuitBreakerEventsEndpointResponse(getCircuitBreakerEvents(name)
.filter(event -> event.getEventType() == CircuitBreakerEvent.Type
.valueOf(eventType.toUpperCase()))
.map(CircuitBreakerEventDTOFactory::createCircuitBreakerEventDTO).toJavaList());
}
@ReadOperation
public BulkheadEndpointResponse getAllBulkheads() {
List<String> bulkheads = bulkheadRegistry.getAllBulkheads()
.map(Bulkhead::getName)
.appendAll(threadPoolBulkheadRegistry
.getAllBulkheads()
.map(ThreadPoolBulkhead::getName)).sorted().toJavaList();
return new BulkheadEndpointResponse(bulkheads);
}
@ReadOperation
public BulkheadEventsEndpointResponse getAllBulkheadEvents() {
java.util.List<BulkheadEventDTO> response = eventConsumerRegistry.getAllEventConsumer()
.flatMap(CircularEventConsumer::getBufferedEvents)
.sorted(Comparator.comparing(BulkheadEvent::getCreationTime))
.map(BulkheadEventDTOFactory::createBulkheadEventDTO)
.toJavaList();
return new BulkheadEventsEndpointResponse(response);
}
@ReadOperation
public BulkheadEventsEndpointResponse getEventsFilteredByBulkheadName(
@Selector String bulkheadName) {
java.util.List<BulkheadEventDTO> response = getBulkheadEvent(bulkheadName)
.map(BulkheadEventDTOFactory::createBulkheadEventDTO)
.toJavaList();
return new BulkheadEventsEndpointResponse(response);
}
@ReadOperation
public BulkheadEventsEndpointResponse getEventsFilteredByBulkheadNameAndEventType(
@Selector String bulkheadName, @Selector String eventType) {
java.util.List<BulkheadEventDTO> response = getBulkheadEvent(bulkheadName)
.filter(event -> event.getEventType() == BulkheadEvent.Type
.valueOf(eventType.toUpperCase()))
.map(BulkheadEventDTOFactory::createBulkheadEventDTO)
.toJavaList();
return new BulkheadEventsEndpointResponse(response);
}