上一篇文章是关于 “spring boot +RabbitMQ +InfluxDB+Grafara监控实践” 主要讲spring boot应用新能监控信息的收集方案实践

  实践是hystrix信息推送的mq而metrics信息需要扫描,文章的最后也有相应的思考metrics信息能不能是应用本身也推送到mq那?

  本篇文章就实践关于metrics信息的推送实现

 

  有了上面的思考之后我就回过头来去看hystrix是怎么实现推送的。经过一番跟踪之后找到了具体干活的task代码

  

  有了这个代码就可以参考具体怎样实现metrics信息的推送了

  但是还有一个问题就是metrics信息虽然暴露了url接口但是应用内我怎么获取那???

  这里又引发了我们一探究竟的兴趣!。。。。。。继续看源码!!!!!!!!!!!

  从spring boot启动展示的日志中我们可以发现线索,具体/metrics路径具体执行的是哪里

  

  1. Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()

  从org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()这里我们发现了端倪

  好的 我们就去这个包去找相关线索

  

  好的我们找到了这个包往下看

  终于找到他了这里我们就可以用定时器进行轮训调用了。基础准备已经ok,好了不多说了直接上写好的代码

  1. package com.zjs.mic.metrics.stream;
  2. import javax.annotation.PostConstruct;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint;
  5. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  6. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  7. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  8. import org.springframework.cloud.client.ServiceInstance;
  9. import org.springframework.cloud.client.actuator.HasFeatures;
  10. import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClient;
  11. import org.springframework.cloud.client.serviceregistry.Registration;
  12. import org.springframework.cloud.context.config.annotation.RefreshScope;
  13. import org.springframework.cloud.stream.annotation.EnableBinding;
  14. import org.springframework.cloud.stream.annotation.Output;
  15. import org.springframework.cloud.stream.config.BindingProperties;
  16. import org.springframework.cloud.stream.config.BindingServiceProperties;
  17. import org.springframework.context.annotation.Bean;
  18. import org.springframework.context.annotation.Configuration;
  19. import org.springframework.messaging.MessageChannel;
  20. import org.springframework.scheduling.annotation.EnableScheduling;
  21. @RefreshScope
  22. @Configuration
  23. @ConditionalOnClass({EnableBinding.class })
  24. @ConditionalOnProperty(value = "metrics.stream.queue.enabled", matchIfMissing = true)
  25. @EnableConfigurationProperties
  26. @EnableScheduling
  27. @EnableBinding(MetricsStreamClient.class)
  28. public class MetricsStreamAutoConfiguration {
  29. @Autowired
  30. private BindingServiceProperties bindings;
  31. @Autowired
  32. private MetricsStreamProperties properties;
  33. @Autowired
  34. @Output(MetricsStreamClient.OUTPUT)
  35. private MessageChannel outboundChannel;
  36. @Autowired(required = false)
  37. private Registration registration;
  38. @Autowired
  39. MetricsMvcEndpoint mme;
  40. @Bean
  41. public HasFeatures metricsStreamQueueFeature() {
  42. return HasFeatures.namedFeature("Metrics Stream (Queue)",
  43. MetricsStreamAutoConfiguration.class);
  44. }
  45. @PostConstruct
  46. public void init() {
  47. BindingProperties outputBinding = this.bindings.getBindings()
  48. .get(MetricsStreamClient.OUTPUT);
  49. if (outputBinding == null) {
  50. this.bindings.getBindings().put(MetricsStreamClient.OUTPUT,
  51. new BindingProperties());
  52. }
  53. BindingProperties output = this.bindings.getBindings()
  54. .get(MetricsStreamClient.OUTPUT);
  55. if (output.getDestination() == null) {
  56. output.setDestination(this.properties.getDestination());
  57. }
  58. if (output.getContentType() == null) {
  59. output.setContentType(this.properties.getContentType());
  60. }
  61. }
  62. @Bean
  63. public MetricsStreamTask metricsStreamTask(SimpleDiscoveryClient simpleDiscoveryClient) {
  64. ServiceInstance serviceInstance = this.registration;
  65. if (serviceInstance == null) {
  66. serviceInstance = simpleDiscoveryClient.getLocalServiceInstance();
  67. }
  68. return new MetricsStreamTask(this.outboundChannel, serviceInstance,
  69. this.properties,this.mme);
  70. }
  71. }

View Code

  1. package com.zjs.mic.metrics.stream;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. @ConfigurationProperties("metrics.stream.queue")
  4. public class MetricsStreamProperties {
  5. private boolean enabled = true;
  6. private boolean prefixMetricName = true;
  7. private boolean sendId = true;
  8. private String destination = "springCloudMetricsStream";
  9. private String contentType = "application/json";
  10. private String pathTail = "mem.*|heap.*|threads.*|gc.*|nonheap.*|classes.*";
  11. private long sendRate = 1000;
  12. private long gatherRate = 1000;
  13. private int size = 1000;
  14. public String getPathTail() {
  15. return pathTail;
  16. }
  17. public void setPathTail(String pathTail) {
  18. this.pathTail = pathTail;
  19. }
  20. public boolean isEnabled() {
  21. return enabled;
  22. }
  23. public void setEnabled(boolean enabled) {
  24. this.enabled = enabled;
  25. }
  26. public boolean isPrefixMetricName() {
  27. return prefixMetricName;
  28. }
  29. public void setPrefixMetricName(boolean prefixMetricName) {
  30. this.prefixMetricName = prefixMetricName;
  31. }
  32. public boolean isSendId() {
  33. return sendId;
  34. }
  35. public void setSendId(boolean sendId) {
  36. this.sendId = sendId;
  37. }
  38. public String getDestination() {
  39. return destination;
  40. }
  41. public void setDestination(String destination) {
  42. this.destination = destination;
  43. }
  44. public String getContentType() {
  45. return contentType;
  46. }
  47. public void setContentType(String contentType) {
  48. this.contentType = contentType;
  49. }
  50. public long getSendRate() {
  51. return sendRate;
  52. }
  53. public void setSendRate(long sendRate) {
  54. this.sendRate = sendRate;
  55. }
  56. public long getGatherRate() {
  57. return gatherRate;
  58. }
  59. public void setGatherRate(long gatherRate) {
  60. this.gatherRate = gatherRate;
  61. }
  62. public int getSize() {
  63. return size;
  64. }
  65. public void setSize(int size) {
  66. this.size = size;
  67. }
  68. }

View Code

  1. package com.zjs.mic.metrics.stream;
  2. import java.io.StringWriter;
  3. import java.util.ArrayList;
  4. import java.util.Map;
  5. import java.util.concurrent.LinkedBlockingQueue;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint;
  9. import org.springframework.cloud.client.ServiceInstance;
  10. import org.springframework.messaging.MessageChannel;
  11. import org.springframework.messaging.MessageHeaders;
  12. import org.springframework.messaging.support.MessageBuilder;
  13. import org.springframework.scheduling.annotation.EnableScheduling;
  14. import org.springframework.scheduling.annotation.Scheduled;
  15. import org.springframework.util.Assert;
  16. import com.fasterxml.jackson.core.JsonFactory;
  17. import com.fasterxml.jackson.core.JsonGenerator;
  18. @EnableScheduling
  19. public class MetricsStreamTask {
  20. private final static Logger log = LoggerFactory.getLogger(MetricsStreamTask.class);
  21. private MessageChannel outboundChannel;
  22. private ServiceInstance registration;
  23. private MetricsStreamProperties properties;
  24. private MetricsMvcEndpoint mme;
  25. // Visible for testing
  26. final LinkedBlockingQueue<String> jsonMetrics;
  27. private final JsonFactory jsonFactory = new JsonFactory();
  28. public MetricsStreamTask(MessageChannel outboundChannel,
  29. ServiceInstance registration, MetricsStreamProperties properties, MetricsMvcEndpoint mme) {
  30. Assert.notNull(outboundChannel, "outboundChannel may not be null");
  31. Assert.notNull(registration, "registration may not be null");
  32. Assert.notNull(properties, "properties may not be null");
  33. Assert.notNull(mme, "properties may not be null");
  34. this.outboundChannel = outboundChannel;
  35. this.registration = registration;
  36. this.properties = properties;
  37. this.jsonMetrics = new LinkedBlockingQueue<>(properties.getSize());
  38. this.mme=mme;
  39. }
  40. // TODO: use integration to split this up?
  41. @Scheduled(fixedRateString = "${metrics.stream.queue.sendRate:1000}")
  42. public void sendMetrics() {
  43. log.info("推送metrics信息");
  44. ArrayList<String> metrics = new ArrayList<>();
  45. this.jsonMetrics.drainTo(metrics);
  46. if (!metrics.isEmpty()) {
  47. if (log.isTraceEnabled()) {
  48. log.trace("sending stream Metrics metrics size: " + metrics.size());
  49. }
  50. for (String json : metrics) {
  51. // TODO: batch all metrics to one message
  52. try {
  53. // TODO: remove the explicit content type when s-c-stream can handle
  54. // that for us
  55. this.outboundChannel.send(MessageBuilder.withPayload(json)
  56. .setHeader(MessageHeaders.CONTENT_TYPE,
  57. this.properties.getContentType())
  58. .build());
  59. }
  60. catch (Exception ex) {
  61. if (log.isTraceEnabled()) {
  62. log.trace("failed sending stream Metrics metrics: " + ex.getMessage());
  63. }
  64. }
  65. }
  66. }
  67. }
  68. @Scheduled(fixedRateString = "${metrics.stream.queue.gatherRate:1000}")
  69. public void gatherMetrics() {
  70. log.info("开始获取metrics信息");
  71. try {
  72. StringWriter jsonString = new StringWriter();
  73. JsonGenerator json = this.jsonFactory.createGenerator(jsonString);
  74. json.writeStartObject();
  75. json.writeObjectField("instanceId",registration.getServiceId() + ":" + registration.getHost() + ":"
  76. + registration.getPort());
  77. json.writeObjectField("type", "metrics");
  78. json.writeObjectField("currentTime",System.currentTimeMillis());
  79. @SuppressWarnings("unchecked")
  80. Map<String, Object> map = (Map<String, Object>) mme.value(this.properties.getPathTail());
  81. for (String str : map.keySet()) {
  82. json.writeObjectField(str, map.get(str));
  83. }
  84. json.writeEndObject();
  85. json.close();
  86. // output to stream
  87. this.jsonMetrics.add(jsonString.getBuffer().toString());
  88. }
  89. catch (Exception ex) {
  90. log.error("Error adding metrics metrics to queue", ex);
  91. }
  92. }
  93. }

View Code

  1. package com.zjs.mic.metrics.stream;
  2. import org.springframework.cloud.stream.annotation.Output;
  3. import org.springframework.messaging.MessageChannel;
  4. public interface MetricsStreamClient {
  5. String OUTPUT = "metricsStreamOutput";
  6. @Output(OUTPUT)
  7. MessageChannel metricsStreamOutput();
  8. }

View Code

  1. package com.zjs.mic.metrics.stream;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  7. import org.springframework.context.annotation.Import;
  8. @Target(ElementType.TYPE)
  9. @Retention(RetentionPolicy.RUNTIME)
  10. @Import(MetricsStreamAutoConfiguration.class)
  11. @EnableConfigurationProperties({MetricsStreamProperties.class})
  12. public @interface EnableMetricsStream {
  13. }

    已经将上面的代码包装成注解打好包 在入口类加@EnableMetricsStream 注解就能生效

    剩下的就是我们去mq接收信息传递到响应数据库中进行处理就行了

  从而我们在“spring boot +RabbitMQ +InfluxDB+Grafara监控实践” 这篇文章中的图就变成下面这样了

 

    好实践部分就到这里

  总结思考

    监控信息hystrix和metrics到底是拉取好还是主动推送好!一下简单分析:

    拉取,对于被监控的应用来说值引用少量的包节省了推送信息的线程,基本没有什么开发量,对于一些严格权限控制的springboot应用,就需要额外开接口或者拉取进行权限验证很不方便

    推送,应用主动推送应用相关的包和注解占用对应的线程资源,应用可以进行严格的权限控制不用对接口做例外不需要扫描程序开发。

  我的结论是两者并存,不知道大家有没有什么其他想法可以说来听听!

  

 

版权声明:本文为zhyg原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhyg/p/9377406.html