Spring family bucket of spring boot (IV)

    spring boot interceptors, filters, servlet, and health check mechanism

     spring boot interceptor

    Boot interceptor spring arranged substantially the same as the original, but the need to add annotations in the configuration class @Configuration interceptor, so that the interceptor spirng boot spring added to the vessel.

    1, first create a common interceptor before as we like here

package com.scm.mybatis.Interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器的preHandle()方法");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器的postHandle()方法");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器的afterCompletion()方法");
    }

}

 

    2. Create an interceptor class configuration

package com.scm.mybatis.Interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration r = registry.addInterceptor(new MyInterceptor());
        r.addPathPatterns("/*");
        r.excludePathPatterns("/myInterceptor");
    }
}

    One thing to note here is to join @Configuration annotation indicating the class will be added to the spring container. addPathPatterns () indicates a request to intercept, excludePathPatterns () indicate that the request is not intercepted. Of course, we can create multiple interceptors, plus the configuration of the interceptor class @Configuration to comment.

    3. Create a controller

package com.scm.mybatis.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class InController {
    @GetMapping("/Interceptor")
    public String Interceptor1(){
        return "The request is intercepted";//被拦截的请求
    }
    @GetMapping("/myInterceptor")
    public String Interceptor2(){
        return "The request is not intercepted";//不被拦截的请求
    }
}

    After you enter the appropriate url in the browser for testing. "Interceptor" request will output "The request is intercepted", "myInterceptor" request output "The request is not intercepted".

    Filter spring boot (both)

 

    Method 1: Create an ordinary filter

    1, first create a common filter, the filter we have to filter out requests, we add on a custom filter @WebFilter comment.

package com.scm.mybatis.Filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器init()方法");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throwsIOException, ServletException { 
        System.out.println ( "Filter the doFilter () method" ); 
    } 

    @Override 
    public  void destroy () { 
        System.out.println ( "Filter destroy () method" ); 
    } 
}

 

    2, then we start on addition of an entry in the main function @ServletComponentScan annotation, then the annotation together with spring boot servlet scans all relevant annotations. For example, @ WebServlet, @ WebFilter, @ WebListener , annotation parameters is our custom filter pack of lies.

package com.scm.mybatis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan("com.scm.mybatis.Filter")
public class Application {

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

}

    3, create a controller Filter

package com.scm.mybatis.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class filterController {
    @GetMapping("/myFilter")
    public String filterTest(){
        return "This is a Filter";
    }
}

    Of course, we can also, upon request we need to filter out the demand, only need to modify the parameters @WebFilter () in on it, not here at the show.

 

    Second way: Create a configuration like a filter, do not need to comment on MyFilter @WebFilter here, start the class does not need @ServletComponentScan annotated, is the need to add a different filter configuration category.

package com.scm.mybatis.Filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean myFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new MyFilter());
        registration.addUrlPatterns("/*");
        return registration;
    }
}

    @Bean tag is equivalent to the label before spring bean configuration file. The second way in just the first way you want MyFilter class in @WebFilter remove other content, like annotations, @ServletComponentScan should be deleted on startup class, the same controller and the first way.

 

    spring boot配置servlet

    spring boot configuration servlet same filter configuration, the same two ways.

    One way: by @WebServlet notes and @ServletComponentScan

    1, first create a servlet, there is also a plus in the class MyServlet @WebServlet comment.

package com.scm.mybatis.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = -4134217146900871026L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().print("This is my servlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

    2, the main function to start entry plus @ServletComponentScan comment, we said before the annotation can be scanned into @WebServlet comment. 

package com.scm.mybatis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan("com.scm.mybatis.servlet")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

    

    Second way: create a servlet class configuration

    Here we will write servlet request parameter within ServletRegistrationBean () method.

package com.scm.mybatis.servlet;

import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServletConfig {
    @Bean
    public ServletRegistrationBean myServletRegistrationBean(){
        ServletRegistrationBean registration = new ServletRegistrationBean(new MyServlet(), "/myServlet");
        return registration;
    }
}

    After @WebServlet and in a way @ServletComponentScan delete notes, other are the same.

    

    spring boot health check mechanism

   Health check mechanism in the development phase we use is not large, but later deploy the project to a production environment is necessary to carry out the operation and maintenance of the project, then it will use the health check mechanism, the mechanism through which we can monitor real-time status of the project. In a production environment, require the availability of real-time monitoring program, after the problems we need to quickly locate, spring-boot feature provides the actuator required a lot of monitoring interface. actuator function is an integrated application system of self-examination and monitoring of spring boot provided, can be configured to view the application system, health checks, statistics and other related functions; convenient operation and maintenance personnel view the health status of spring boot.

    Use actuator (client side)

   spring boot for the actuator provides a starting rely starter, we need to add the following starter in the pom.

<!--web依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--添加actuator依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--spring boot admin依赖 该依赖是集成的,而不是spring官方的-->
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
</dependency>

    If you do not want to manually add, the more we rely on to check when you create a module, pom.xml after the check will be generated automatically dependent.

  

    我们先创建一个actuator-client,在client端中添加完相关依赖之后我们只需要在application.properties添加相关配置项即可。

#设置actuator监控端口
management.server.port=8088

#开启所有监控,默认只开启health和info
management.endpoints.web.exposure.include=*

#添加info信息
info.author=scm
info.url=www.baidu.com

    上述代码分析:

    1、般程序运行默认端口为8080,这里我们将actuator-client端口设置为8088。

     2、management.endpoints.web.exposure.include作用是开启所有的监控,里边有项目的一些信息,默认只开启了health和info,还有其他如bean可以查看spring容器中有哪些bean对象。如果想要具体了解可以查看spring官网文档,地址如下。从文档部分截图看出health和info是默认开启的。

     https://docs.spring.io/spring-boot/docs/2.1.7.RELEASE/reference/html/production-ready-endpoints.html

    

    3、上边说到了info,那么在actuator中info到底是什么呢?Info其实就是开发者自定义的一些信息。例如我们在上述代码中写入了info.author和info.url(info.后的参数可以是任意的),启动spring boot之后,我们可以在浏览器中输入如下代码查看相关信息。注意输入时端口号要与配置文件中端口号一致,端口号之后要加上actuator。也可以将info改为health和bean查看其他相关信息。如果我们在配置文件中没有开启所有监控那么除了info和health之外其他是无法查看的。

http://localhost:8088/actuator/info

     在actuator中提供了很多接口,通过这些接口可以监控一些信息,这里列举一部分:

    •   beans

        展示了bean的别名、类型、是否单例、类的地址、依赖等信息。

    •   env

        展示了系统环境变量的配置信息,包括使用的环境变量、JVM 属性等。

    •   health

        描述了应用程序的整体健康状态,UP 表明应用程序是健康的。

    •   mappings

        URl路径和控制器的映射关系。

    

    spring boot admin图形化界面(server端)

     上面通过actuator提供的rest接口,返回的数据都是json格式,这个对于不懂json格式的人来说不太方便,因此就产生了spring boot admin,它提供了图形化界面,通过界面来展示这些数据。在actuator-client客户端一般放入一些业务逻辑,通常会再创建一个actuator-server服务端来专用于监控。

    以下是需要添加的相关依赖,或在创建模块时直接勾选,无需手动添加。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

    与之前不一样的是这里我们需要勾选Server,之前我们勾选的是Client。

    

    1、创建完actuator-server之后需要在application.properties配置文件中配置服务端端口

#server端端口号
server.port=8089

    2、在actuator-server的主函数启动入口上需要加上@EnableAdminServer注解用于开启SBA服务。 

package com.monkey.server;

import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAdminServer//开启SBA服务
public class ApplicationServer {

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

    上面的项目是作为server端,将之前的spring boot项目作为client端,由server端统一监控client端。client的模块中,在配置文件里面添加下面内容:

    3、在actuator-client端的application.properties配置文件中我们还需要指定服务端的主机地址,添加如下代码:

#配置actuator admin主机地址
spring.boot.admin.client.url=http://localhost:8089

    全部完成之后,启动server和client,访问server端,http://localhost:8089 就可以看到spring boot admin的页面了。访问的地址为actuator-server端的端口号。

    

   健康检查机制总结:

    1、需要创建actuator-clietn和actuator-server两个模块(client端可以创建多个,如果创建多个在server端都可以看到),两个模块所添加的依赖不完全相同,具体参考上述。

     2、client需要配置client端端口号、开启所有监控服务、可以使用info添加自定义信息、还要指定server端的地址。

     3、server需要配置server端端口号、在主函数启动入口添加@EnableAdminServer注解用于开启SBA服务。

     4、通过地址栏访问client端时要在端口号之后加上actuator,之后加上rest接口名。要想访问server端直接输入server端口号即可,但要将client和server端两个启动入口同时开启。

    

    

    

 

    

    

 

 

   

    

 

Guess you like

Origin www.cnblogs.com/scm2019/p/11331261.html