Spring boot monitoring component actuator combined with consul registration center use summary

Recent projects have used spring boot. Compared with the previous use of spring, it is indeed much more convenient. It is no longer necessary to introduce each jar package dependency separately. You only need to introduce the initial dependencies required by spring boot. The automatic configuration of spring boot will help us. Things to rely on are done. Spring boot also supports conditional configuration, that is, you can use a custom configuration to override the automatic configuration. such as:

    @Bean
    @ConditionalOnMissingBean({JdbcOperations.class})
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(this.dataSource);
    }

The conditional annotation @ConditionalOnMissingBean is used here, which means that the JdbcTemplate bean will be created only if the bean instance of JdbcOperations (ie the interface implemented by JdbcTemplate) is not found under the classpath. If an instance of JdbcOperations already exists, this automatic configuration is not effective and will be overwritten.

Here we mainly talk about Actuator, a monitoring component of spring boot, which can monitor your application. With the actuator, you can know how the beans are assembled together in the spring context, understand the environment attribute information at all times, and obtain snapshots of runtime measurement information.
Actuator provides 13 endpoints, which can be divided into three categories: configuration endpoints, measurement endpoints and other endpoints: as shown below

Insert picture description here
Gradle depends on the following:

compile ‘org.springframework.boot:spring-boot-starter-actuator’
  
maven引入以下依赖:

org.springframework.boot
spring-boot-starter-actuator

Add in the yml file:

management:
  context-path: /mgmt

After starting the application, the browser enters: http://localhost:8080/mgmt/autoconfig to view the conditional configuration passed and the
Insert picture description here
other endpoints of the failed bean can be viewed in this way.

As an important part of the system, monitoring cannot be open to everyone, so it needs control authority, which can be controlled by spring security.
Introduce initial dependency:

  compile("org.springframework.boot:spring-boot-starter-security")

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private ReaderRepository readerRepository;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        .antMatchers("/").access("hasRole('READER')")
        .antMatchers("/mgmt/**").access("hasRole('ADMIN')")
        .antMatchers("/**").permitAll()
      .and()
      .formLogin()
        .loginPage("/login")
        .failureUrl("/login?error=true");
  }

  @Override
  protected void configure(
              AuthenticationManagerBuilder auth) throws Exception {
    auth
      .userDetailsService(new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
          UserDetails user = readerRepository.findOne(username);
          if (user != null) {
            return user;
          }
          throw new UsernameNotFoundException("User '" + username + "' not found.");
        }
      })
      .and()
      .inMemoryAuthentication()
        .withUser("manager").password("s3cr3t").roles("ADMIN");
  }

}

In this way, a user with the role of ROLE_ADMIN is allocated in memory, and only users with this role have permission to access the actuator endpoint.

Actuator’s metrics provide metrics (metrics endpoints) to help us better understand the application situation, but sometimes we need additional metrics, which can be customized at this time. The CounterService interface defines 3 methods, which are used to increase, decrease, and reset the metric value of a specific name, as follows:

public interface CounterService{
  void increment(String metricName);
  void decrement(String metricName);
  void reset(String metricName);
}

You can also use the submit method of the GaugeService interface to record a value into the metric value of the specified name.

public interface GaugeService{
  void submit(String metricName, double value);
}

View the actuator can also connect to the remote shell mode.
Replace compile'org.springframework.boot:spring-boot-starter-actuator' with gradle dependency

compile("org.springframework.boot:spring-boot-starter-remote-shell")

After starting the program, connect via ssh, every time the program is started, a password will be generated, the format is:
Using default security password: a3fca416-76ed-4098-bf8a-285988841693

View endpoint: autoconfig (support autoconfig, beans, metrics), other endpoints can
support the following endpoints through endpoint invoke xxx. For Insert picture description here
example, if you want to see health, then endpoint invoke health

The autoconfig endpoint is as shown in the
figure: Insert picture description here
if you don’t want to enable all endpoints, you can configure it through properties or in yml

endpoints:
  metrics:
    enabled: false

If you only want to turn on metrics, turn off everything else

endpoints:
  enabled: false
  metrics:
    enabled: true

split line------------------------------------------------ -------------------------------------------------- -----------------------In the
past few days, I discovered that the application can also be monitored through the graphical interface, and I have specially added it

Service discovery uses consul. All spring boot applications are registered on consul, which is mainly achieved by introducing spring-boot-admin-starter-client: 2.0.4 and spring-boot-admin-starter-server: 2.0.4

Note: It is necessary to start the consul server, which will not be explained here, -_-

The server side (an independent application) is configured as follows:
bulid.gradle introduces dependencies:

    compile ('de.codecentric:spring-boot-admin-starter-server:2.0.4')
    compile ('org.springframework.boot:spring-boot-starter-security')
    compile ('io.netty:netty-transport-native-epoll:4.1.15.Final')

yml file:

server:
  port: 19500
  logger:
    level:
      console: INFO

consul-server-ip-address: 192.168.x.xx #consul服务地址

management:
  endpoints:
    beans:
      enabled: false
    web:
      exposure:
        include: "*"
  endpoint:
      health:
        show-details: ALWAYS

spring:
  application:
    name: server-ms-admin
  cloud:
    consul:
      host: ${consul-server-ip-address}
      port: 18300
      discovery:
        prefer-ip-address: true
        service-name: ${spring.application.name}
        hostname: ${spring.cloud.client.ip-address}
        port: ${server.port}
        health-check-interval: 10s
        heartbeat:
          enabled: true
  profiles:
    active:
      - secure
  boot:
    admin:
      discovery:
        ignored-services:server-ms-admin, consul


---
spring:
  profiles: insecure

---
spring:
  profiles: secure
  security:
    user:
      name: "admin"  # 设置用户名和密码 
      password: "123"



Start application

@SpringBootApplication
@EnableDiscoveryClient
@EnableAdminServer
public class AdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class, args);
    }

}

Start another monitored application

The configuration is as follows:
(In fact, it is just to import and use maven to import, the following is to use gradle to build
org.springframework.boot:spring-boot-starter-web, org.springframework.boot:spring-boot-starter-security, de.codecentric :spring-boot-admin-starter-client:2.0.4, org.springframework.cloud:spring-cloud-starter-consul-discovery, org.springframework.boot:spring-boot-starter-actuator:2.0.6.RELEASE )

buildscript {
    ext {
        springBootVersion = '2.0.6.RELEASE'
    }
    repositories {
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
        maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

plugins {
    id 'java'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'


group 'com.xx.server'
version = moduleVersion

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile('org.springframework.boot:spring-boot-starter-log4j2')
    compile('org.springframework.boot:spring-boot-starter-security')
    compile('de.codecentric:spring-boot-admin-starter-client:2.0.4')

    compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')


    compile("org.springframework.boot:spring-boot-starter-actuator:2.0.6.RELEASE")



}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

Also start an application application

@SpringBootApplication
@EnableDiscoveryClient
public class Application  {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

Because spring boot accesses spring security by default, every request needs to be authenticated, and the following configuration needs to be added to use (it was also because there was no tossing for a long time at the beginning...)

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll()
                .and().csrf().disable();
    }

}

The yml is as follows:

server:
  port: 19900
  logger:
    level:
      console: INFO
      

consul-server-ip-address: 192.168.X.XX

management:
  security:
    enabled: false
  endpoints:
    beans:
      enabled: false
    web:
      exposure:
        include: "*"


spring:
  #security:
    #user:
      #name: "admin"
      #password: "123"
  application:
    name: kp-huangtest
  messages:
    basename: i18n/messages
    encoding: utf-8
  cloud:
    consul:
      host: ${consul-server-ip-address}
      port: 18500
      discovery:
        prefer-ip-address: true
        service-name: ${spring.application.name}
        hostname: ${spring.cloud.client.ip-address}
        port: ${server.port}
        health-check-interval: 10s
        heartbeat:
          enabled: true

Start the application through access:
Insert picture description here
enter the user name and password to log in and see the following:
Insert picture description here

Click one of them to see the information of each monitoring endpoint:
Insert picture description here

The above is all the content of this summary, there may be errors, please correct me, thank you!

Guess you like

Origin blog.csdn.net/huangdi1309/article/details/86704472