Table of Contents
SpringBoot closes the actuator
SpringBoot actuator knowledge combing
Home Java javaTutorial How to close actuator in SpringBoot

How to close actuator in SpringBoot

May 12, 2023 pm 07:46 PM
springboot actuator

    SpringBoot closes the actuator

    How to close actuator in SpringBoot

    management:
      endpoint:
        health:
          show-details: ALWAYS
      endpoints:
        enabled-by-default: false #关闭监控
        web:
          exposure:
            include: '*'
    Copy after login

    SpringBoot actuator knowledge combing

    Spring Boot’s Actuator . It provides many production-grade features, such as monitoring and measuring Spring Boot applications. These features of Actuator are available through numerous REST endpoints, remote shells, and JMX.

    【Usage environment】

    【1】SpringBoot version 2.5.0, JDK11

    【2】Service port 9999

    Add dependency

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    Copy after login

    Start the project and access the /actuator endpoint. The SpringBoot2. Some endpoints can be set in exclude.

    management:
      endpoints:
        web:
          exposure:
            include: "*"
            exclude: ""
    Copy after login

    Restart the project, you can see that the displayed endpoints have increased a lotHow to close actuator in SpringBoot

    Actuator endpoint arrangement

    How to close actuator in SpringBoot/autoconfig and/conditions Get auto-configuration conditions

    Provides an auto-configuration report to record which auto-configuration conditions passed and which failed. The new version has been adjusted to conditions. Spring Boot automatic configuration is built on Spring's conditional configuration. It provides numerous configuration classes with @Conditional annotations, and determines whether to automatically configure these beans based on conditions. The /autoconfig endpoint provides a report listing all conditions that were evaluated, grouped according to whether the condition passed or failed.

    Endpoint: http://localhost:9999/actuator/conditions

    ##[Example]

    How to close actuator in SpringBoot

    The above is an example of a failed condition, as shown in the figure is JdbcTemplate, this class can help us operate the database. Because the relevant dependent classes are not introduced, just as its prompt message says:

    "message": "@ConditionalOnClass did not find required class ‘org.springframework.jdbc.core.JdbcTemplate’"

    How to close actuator in SpringBoot Check that Classpath does not require JdbcTemplate. If the condition is not met, automatic configuration will not be performed.

    /beans Obtain Bean assembly report

    To understand the Spring context in the application In this case, the most important endpoint is /beans. It returns a JSON document describing each bean in the context, including its Java type and other injected beans.

    Request endpoint:/actuator/beans

    /env endpoint View configuration properties

    How to close actuator in SpringBoot/env endpoint will Generates a list of all environment properties available to the application, whether or not they are used. This includes environment variables, JVM properties, command line parameters, and properties provided by application.properties or application.yml files.

    Endpoint:/actuator/env

    /env provides some security policies to protect the privacy of configuration. In order to prevent such information from being exposed to /env, all attributes named password, secret, key (or the last paragraph of the name are these) will be added with "*" in /env, the reference is as follows:

    How to close actuator in SpringBoot

    /mappingRequest URL mapping

    How to close actuator in SpringBoot/mapping endpoint displays all @RequestMapping request paths

    Request endpoint:/actuator/mappings

    [Test Interface]

        @GetMapping(value = "/hello", produces = "application/json;charset=utf-8")
        public String hello(@RequestParam("name") String name) {
            return "hello world";
        }
    Copy after login

    How to close actuator in SpringBoot

    Each mapped value has two attributes: bean and method. The bean attribute identifies the name of the Spring

    Bean from which the mapping originates. The method attribute is the fully qualified method signature of the mapping corresponding method.

    How to close actuator in SpringBoot

    /metricsRuntime indicator monitoring

    /metrics provides us with a monitoring of runtime metrics, which can quickly check the application at runtime.

    Endpoint:/actuator/metrics

    The main monitoring items are as follows:

    How to close actuator in SpringBoot

    /metrics端点会返回所有的可用度量值,但你也可能只对某个值感兴趣。要获取单个值,请求时可以在URL后加上对应的键名。

    How to close actuator in SpringBoot

    如上图所示,查询jvm最大内存,结果值大约为6G。

    /httptrace 追踪Web请求

    /httptrace端点能报告所有Web请求的详细信息,包括请求方法、路径、时间戳以及请求和响应的头信息。

    【请求端点】/actuator/httptrace

    默认情况下httptrace没有启用,它要求一个HttpTraceRepository 的对象Bean.

    How to close actuator in SpringBoot

    在系统中创建如下配置,提供一个HttpTraceRepository 类型的Bean,这里选择的是InMemoryHttpTraceRepository内存存储的方式。该方式默认提供最新的100条请求记录。

    import org.springframework.boot.actuate.trace.http.HttpTraceRepository;
    import org.springframework.boot.actuate.trace.http.InMemoryHttpTraceRepository;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class HttpTraceActuatorConfiguration {
    
        @Bean
        public HttpTraceRepository httpTraceRepository() {
            return new InMemoryHttpTraceRepository();
        }
    
    }
    Copy after login

    /dump 导出线程快照

    /dump端点会生成当前线程活动的快照。完整的线程导出报告里会包含应用程序的每个线程。其中包含很多线程的特定信息,还有线程相关的阻塞和锁状态。

    【请求端点】/threaddump

    How to close actuator in SpringBoot

    【测试】

         Thread thread = new Thread(() -> {
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "测试线程");
            thread.start();
    Copy after login

    How to close actuator in SpringBoot

    /shutdown 优雅的关闭应用程序

    /shutdown可以让应用服务优雅的关闭,默认是关闭的。假设你要关闭运行中的应用程序。比方说,在微服务架构中,你有多个微服务应用的实例运行在云上,其中某个实例有问题了,你决定关闭该实例并重启这个有问题的应用程序。在这个场景中,Actuator的/shutdown端点就很有用了。

    How to close actuator in SpringBoot

    优雅的关闭和kill -9的方式是相对的,它不会粗暴的立马关闭应用,而是会释放相关链接以及执行SpringBoot容器停止后的一些操作,然后再关闭应用。

    【端点】/actuator/shutdown 要求POST请求方式

    【示例】

    在应用中添加一个关闭前处理的钩子方法

            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("关闭应用,释放资源");
            }));
    Copy after login

    How to close actuator in SpringBoot

    How to close actuator in SpringBoot

    可以看到通过/actuator/shutdown关闭应用可以触发这些关闭处理的钩子函数,方便我们在应用停止时关闭一些连接以及做一些其他的处理。

    整理

    【1】上面实践了一些Actuator端点示例,虽然Actuator提供的功能很强大,但是在如今的集群化,K8S容器化应用部署下,这些直接访问某些应用的情况就变得很少了,比如监控Zipkin 、Spring Cloud Sleuth等等,内存监控这一块K8S容器化平台也有很多。但是,去学习实践这样的一个工具也是很值得的,如果后面有类似监控、关闭应用、获取请求URL映射、获取配置等等,那么我们就可以去看看Actuator是如何做的,学习和扩展。

    【2】本次的学习时看的《SpringBoot实战》书籍的学习笔记,该书Actuator章节后在后面也提及了很多进阶的知识,因为具体应用场景不多,下面就简单的整理下,把一些知识点记录下来,如果后面需要在重点实践学习下。

    【3】《SpringBoot实战》书籍关于Actuator介绍的一些使用可能在当下的版本中有些出入,这里贴上官方文档地址,参考对比下https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html#actuator.enabling

    【4】Actuator通过REST端点提供了不少非常有用的信息。另一个深入运行中应用程序内部的方式是使用远程shell。Spring Boot集成了CRaSH,一种能嵌入任意Java应用程序的shell。Spring Boot还扩展了CRaSH,添加了不少Spring Boot特有的命令,提供了与Actuator端点类似的功能。该工具附上应用上,会在启动时提供一个访问秘钥,我们通过ssh user@localhost -p 2000 的方式就可以去访问,并且执行一些命令去查看应用数据。

    【5】除了REST端点和远程shell,Actuator还把它的端点以MBean的方式发布了出来,可以通过JMX来查看和管理。使用JMX是管理Spring Boot应用程序的一个好方法,如果你已在用JMX管理应用程序中的其他MBean,则尤其如此。

    [6] Earlier we used some of the built-in endpoints provided by Actuator. We can also extend and customize Actuator according to our own needs.

    • In fact, Actuator has many ways to customize it, including the following five.

    • #1: Rename the endpoint. Change the default endpoint to our custom endpoint address.

    • 2: Enable and disable endpoints.

    • 3: Customized measurement information.

    • 4: Create a custom warehouse to store tracking data.

    • 5: Insert a custom health indicator.

    [7] At this point we can see that through Actuator we can see a lot of system information, which is good for developers, but from a security perspective, if not If restrictions are imposed, the security of the system will be greatly compromised. Actuator's endpoint protection can be used in the same way as other URL paths - using Spring Security. In a Spring Boot application, this means adding the Security starter dependency as a build dependency and then letting security-related auto-configuration protect the application, including the Actuator endpoint. For example, you want to protect the /shutdown endpoint and only allow access to users with ADMIN privileges.

    The above is the detailed content of How to close actuator in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

    Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

    How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

    Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

    How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

    1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

    How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

    Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

    How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

    When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

    Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

    SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

    How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

    1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

    How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

    In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

    See all articles