当前位置:   article > 正文

SpringBootAdmin微服务监控_management :health: mail: enabled: false

management :health: mail: enabled: false

创建Server

SpringBootAdmin通过收集actuator暴露出来的服务信息以及通过心跳检测的机制判断服务的运行状况。

1.引入依赖

  1. <dependency>
  2. <groupId>de.codecentric</groupId>
  3. <artifactId>spring-boot-admin-starter-server</artifactId>
  4. <version>2.2.0</version>
  5. </dependency>

2. 启动类手动装配AdminServer

  1. @EnableAdminServer
  2. @SpringBootApplication
  3. public class MicroAdminApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(MicroAdminApplication.class, args);
  6. }
  7. }

3. 配置服务发现

eureka

  1. eureka:
  2. instance:
  3. prefer-ip-address: true
  4. lease-renewal-interval-in-seconds: 5
  5. lease-expiration-duration-in-seconds: 10
  6. instance-id: ${spring.cloud.client.ip-address}:${server.port}
  7. client:
  8. fetch-registry: true
  9. registry-fetch-interval-seconds: 5
  10. serviceUrl:
  11. defaultZone: http://10.2.1.5:9001/eureka/,http://10.2.1.6:9001/eureka/

nacos

  1. spring:
  2. cloud:
  3. nacos:
  4. discovery:
  5. server-addr: 192.168.174.137:8848

服务器端配置完毕!

4. 接入SpringSecurity

保证登录安全,可以不接

引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. </dependency>

指定登录页面为SpringBootAdmin

  1. @Configuration
  2. public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
  3. private final String adminContextPath;
  4. public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
  5. this.adminContextPath = adminServerProperties.getContextPath();
  6. }
  7. @Override
  8. protected void configure(HttpSecurity http) throws Exception {
  9. // @formatter:off
  10. SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
  11. successHandler.setTargetUrlParameter( "redirectTo" );
  12. http.authorizeRequests()
  13. .antMatchers( adminContextPath + "/assets/**" ).permitAll()
  14. .antMatchers( adminContextPath + "/login" ).permitAll()
  15. .anyRequest().authenticated()
  16. .and()
  17. .formLogin().loginPage( adminContextPath + "/login" ).successHandler( successHandler ).and()
  18. .logout().logoutUrl( adminContextPath + "/logout" ).and()
  19. .httpBasic().and()
  20. .csrf().disable();
  21. }
  22. }

配置登录密码

  1. spring:
  2. security:
  3. user:
  4. name: 'admin'
  5. password: 'admin'


Client接入

1. 引入依赖

该依赖已经包含
spring-boot-starter-actuator不需要重复引入

  1. <dependency>
  2. <groupId>de.codecentric</groupId>
  3. <artifactId>spring-boot-admin-starter-client</artifactId>
  4. <version>2.2.0</version>
  5. </dependency>

2. 配置暴露的端点信息

  1. management:
  2. endpoints:
  3. web:
  4. exposure:
  5. include: '*'
  6. endpoint:
  7. health:
  8. show-details: ALWAYS

[注意] 默认会检查redis的健康状况,如果你的服务没有依赖redis,需要额外增加配置,关掉redis的健康检查。否则会报异常。

  1. management:
  2. health:
  3. redis:
  4. enabled: false

依次启动Server和Client,浏览器登录

{port}访问springBootAdmin,此时服务已经接入成功


应用详情可查看应用具体的状况

Server端使用报警提示功能

接入邮箱报警提示

引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-mail</artifactId>
  4. </dependency>

配置邮箱信息

  1. spring:
  2. boot:
  3. admin:
  4. notify:
  5. mail:
  6. to: yuwenbo10@jd.com
  7. from: 18629015421@163.com
  8. mail:
  9. host: smtp.163.com
  10. password: '******'
  11. username: 18629015421@163.com

【注意】 此处的邮箱密码不是我们设定的邮箱密码,需要登录到对应的邮箱官网去设置smtp的授权码,此处参照百度百科
https://jingyan.baidu.com/article/295430f1fc28a60c7e0050f9.html

再次重启admin Server 如果有服务发生任何变动会给配置的邮箱发送邮件 eg:

自定义报警

SpringBootAdmin 发送邮件的原理是基于事件的监听机制,类似于观察者模式,具体的类 
de.codecentric.boot.admin.server.notify.MailNotifier 部分源码如下:

  1. public class MailNotifier extends AbstractStatusChangeNotifier {
  2. private final JavaMailSender mailSender;
  3. private final TemplateEngine templateEngine;
  4. private String[] to = new String[]{"root@localhost"};
  5. private String[] cc = new String[0];
  6. private String from = "Spring Boot Admin <noreply@localhost>";
  7. private Map<String, Object> additionalProperties = new HashMap();
  8. @Nullable
  9. private String baseUrl;
  10. private String template = "classpath:/META-INF/spring-boot-admin-server/mail/status-changed.html";
  11. public MailNotifier(JavaMailSender mailSender, InstanceRepository repository, TemplateEngine templateEngine) {
  12. super(repository);
  13. this.mailSender = mailSender;
  14. this.templateEngine = templateEngine;
  15. }
  16. /**
  17. * 服务发送变动,会调用该方法发送邮件
  18. */
  19. protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
  20. return Mono.fromRunnable(() -> {
  21. Context ctx = new Context();
  22. ctx.setVariables(this.additionalProperties);
  23. ctx.setVariable("baseUrl", this.baseUrl);
  24. ctx.setVariable("event", event);
  25. ctx.setVariable("instance", instance);
  26. ctx.setVariable("lastStatus", this.getLastStatus(event.getInstance()));
  27. try {
  28. MimeMessage mimeMessage = this.mailSender.createMimeMessage();
  29. MimeMessageHelper message = new MimeMessageHelper(mimeMessage, StandardCharsets.UTF_8.name());
  30. message.setText(this.getBody(ctx).replaceAll("\\s+\\n", "\n"), true);
  31. message.setSubject(this.getSubject(ctx));
  32. message.setTo(this.to);
  33. message.setCc(this.cc);
  34. message.setFrom(this.from);
  35. this.mailSender.send(mimeMessage);
  36. } catch (MessagingException var6) {
  37. throw new RuntimeException("Error sending mail notification", var6);
  38. }
  39. });
  40. }
  41. .....次数省略若干行
  42. }

1.自定义邮件模板

可以看出邮件模板的存放路径是


/META-INF/spring-boot-admin-server/mail/status-changed.html 我们可以在自己项目目录下创建模板进行替换。

2. 更改邮件级别

不知道标题写啥,就写级别吧,默认情况下服务的上线,下线,离线,未知,等等状态都会发邮件,服务的状态在类Instance的StatusInfo里面使用6个String类型的常量来进行描述

部分源码:

  1. public final class StatusInfo implements Serializable {
  2. public static final String STATUS_UNKNOWN = "UNKNOWN";
  3. public static final String STATUS_OUT_OF_SERVICE = "OUT_OF_SERVICE";
  4. public static final String STATUS_UP = "UP";
  5. public static final String STATUS_DOWN = "DOWN";
  6. public static final String STATUS_OFFLINE = "OFFLINE";
  7. public static final String STATUS_RESTRICTED = "RESTRICTED";
  8. .....
  9. }

我们可以继承抽象类
AbstractStatusChangeNotifier并重写doNotify方法,定制化邮件发送。

3. 做点别的?

有时候我们想既发送邮件,也发送短信的形式来保证服务出现问题第一时间感知,我们可以自己编写一个类继承
AbstractStatusChangeNotifier实现onNotify方法具体写自己的短信逻辑就可以了,但是我们会发现,这样操作的话,每次只会发送短信,不会发送默认的邮件了,这是由于mailNotifier使用自动装配机制(不了解自动装配的可以查看这篇文章https://www.jianshu.com/p/c56c34c1c876 ),并通过@ConditionOnMissingBean注解控制,如果Spring容器中有AbstractStatusChangeNotifier实例了,就不会注入mailNotifier,具体的解决方案可以是这样的,复制他的代码,然后去掉@ConditionOnMissingBean注解就可以了。

  1. @Configuration
  2. public class BeanFactory {
  3. @AutoConfigureBefore({AdminServerNotifierAutoConfiguration.NotifierTriggerConfiguration.class, AdminServerNotifierAutoConfiguration.CompositeNotifierConfiguration.class})
  4. @ConditionalOnBean({MailSender.class})
  5. public static class MailNotifierConfiguration {
  6. private final ApplicationContext applicationContext;
  7. public MailNotifierConfiguration(ApplicationContext applicationContext) {
  8. this.applicationContext = applicationContext;
  9. }
  10. @Bean
  11. @ConfigurationProperties("spring.boot.admin.notify.mail")
  12. public MailNotifier mailNotifier(JavaMailSender mailSender, InstanceRepository repository) {
  13. return new MailNotifier(mailSender, repository, this.mailNotifierTemplateEngine());
  14. }
  15. @Bean
  16. public TemplateEngine mailNotifierTemplateEngine() {
  17. SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
  18. resolver.setApplicationContext(this.applicationContext);
  19. resolver.setTemplateMode(TemplateMode.HTML);
  20. resolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
  21. SpringTemplateEngine templateEngine = new SpringTemplateEngine();
  22. templateEngine.addTemplateResolver(resolver);
  23. return templateEngine;
  24. }
  25. }
  26. }

4.分布式监控

这里只说一点点,就是我们生产环境,一般SpringBootAdmin Server也需要进行集群部署,但是如果服务发生问题,相同的邮件会发送多份,所以需要使用分布式锁的机制,如果你的分布式锁是基于AOP实现,不能直接放在onNotify方法上,因为这个方法的访问权限是protected,需要将方法的访问级别提升为public,可能也不好使,还是使用编码的形式吧~
作者:茶还是咖啡
链接:
https://www.jianshu.com/p/9b9145eec05a

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/125596
推荐阅读
相关标签
  

闽ICP备14008679号