Spring全家桶之spring boot(四)

    spring boot拦截器、过滤器、servlet和健康检查机制

     spring boot拦截器

    spring boot配置拦截器与原来大致相同,只是需要在拦截器的配置类上添加@Configuration注解,让spirng boot将拦截器加入spring容器中。

    1、首先这里我们像之前一样创建一个普通的拦截器

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、创建一个拦截器配置类

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");
    }
}

    这里需要注意的一点就是要加入@Configuration注解,表示该类会被加入到spring容器中。addPathPatterns()表示要拦截的请求,excludePathPatterns()表示不拦截的请求。当然我们可以创建多个拦截器,在拦截器的配置类上加上@Configuration注解即可。

    3、创建一个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";//不被拦截的请求
    }
}

    之后在浏览器中输入相应的url进行测试。"Interceptor" 请求会输出 "The request is intercepted", "myInterceptor"请求输出" The request is not intercepted"。

    spring boot过滤器(两种方式)

    方式一:创建普通的filter

    1、首先创建一个普通的过滤器,过滤器中我们过滤掉有请求,我们在自定义的过滤器上加上一个@WebFilter注解。

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) throws IOException, ServletException {
        System.out.println("过滤器doFilter()方法");
    }

    @Override
    public void destroy() {
        System.out.println("过滤器destroy()方法");
    }
}

    2、接着我们在主函数启动入口上加入一个@ServletComponentScan注解,加上该注解之后spring boot会扫描servlet相关的所有注解。比如@WebServlet、@WebFilter、@WebListener,注解中的参数就是我们自定义过滤器的所在包。

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、创建Filter的controller

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";
    }
}

    当然我们还可根据需求过滤掉我们所需要的请求,只需要修改@WebFilter()中的参数就可以了,这里就不在展示了。

    方式二:创建一个过滤器的配置类,这里MyFilter上不需要@WebFilter注解,启动类上也不需要@ServletComponentScan注解了,不同的就是需要添加一个过滤器配置类。

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标签就相当于以前spring配置文件中的bean标签。第二种方式中只需要将第一种方式的MyFilter类中的@WebFilter注解删除其他内容一样,启动类上的@ServletComponentScan也要删除,controller与第一种方式相同。

    spring boot配置servlet

    spring boot配置servlet与配置过滤器相同,同样有两种方式。

    方式一:通过@WebServlet和@ServletComponentScan注解

    1、首先创建一个servlet,这里同样是在MyServlet类上加上@WebServlet注解。

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、在主函数启动入口加上@ServletComponentScan注解,之前我们说过该注解可以扫描到@WebServlet注解。 

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);
    }
}

    

    方式二:创建一个servlet配置类

    这里我们将servlet请求参数写在ServletRegistrationBean()方法内。

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;
    }
}

    将方式一中@WebServlet和@ServletComponentScan注解删除之后,其他均相同。

    

    spring boot健康检查机制

   健康检查机制在我们开发阶段用处并不大,但是将项目部署到生产环境之后就要对项目进行运维,这时就会用到健康检查机制,通过该机制我们可以实时监控项目的状态。在生产环境中,需要实时监控程序的可用性,出现问题之后我们需要快速定位,spring-boot 的 actuator 功能提供了很多监控所需的接口。actuator是spring boot提供的对应用系统的自省和监控的集成功能,可以对应用系统进行配置查看、健康检查、相关功能统计等;方便运维人员查看spring boot的运行状况。

    使用actuator(client端)

   spring boot为actuator提供了起步依赖starter,我们需要在pom中添加下面starter。

<!--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>

    如果不想手动添加,我们在创建模块时将以上依赖勾选即可,勾选后pom.xml中会自动生成相关依赖。

  

    我们先创建一个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端两个启动入口同时开启。

    

    

    

    

    

   

    

原文地址:https://www.cnblogs.com/scm2019/p/11331261.html

时间: 2024-08-30 12:15:56

Spring全家桶之spring boot(四)的相关文章

Spring全家桶之spring boot(三)

spring boot集成mybatis 众所周知,spring与springmvc可以无缝集成,而mybatis不是spring旗下的框架,因此需要进行配置,当然,这里的配置也是非常简单的. 1.首先我们需要创建一个数据库表: CREATE TABLE `learnmybatis`.`t_student` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(20) NULL, `age` INT NULL, `score` DOUBLE NUL

【转】Spring全家桶

Spring框架自诞生以来一直备受开发者青睐,有人亲切的称之为:Spring 全家桶.它包括SpringMVC.SpringBoot.Spring Cloud.Spring Cloud Dataflow等解决方案. 很多研发人员把spring看作心目中最好的java项目,没有之一. 所以这是重点也是难点,工作中必须会,面试时肯定考. 那么,今天花费20分钟,梳理Spring框架相关知识. Spring系列包含非常多的项目,可以满足java开发中的方方面面. 先来看常用框架的知识点汇总,如图: Ⅰ

Spring全家桶带来云时代的软件开发变革

快速发展和变化的业务需求所带来的挑战正在驱动现代企业数字化转型,云原生应用系统的构建是其中最为重要环节之一. 目前,云原生应用开发框架Spring(包括Spring MVC.Spring Boot.Spring Cloud.Spring Cloud Dataflow)已经占据Java软件开发框架的统治地位.在Snyk最新的2018 JVM生态调查中表明:40%被调研的开发者正在使用Spring Boot,36%被调研的开发者正在使用Spring MVC:2018年也是Spring Boot首次超

Spring全家桶——SpringBoot之AOP详解

Spring全家桶--SpringBoot之AOP详解 面向方面编程(AOP)通过提供另一种思考程序结构的方式来补充面向对象编程(OOP). OOP中模块化的关键单元是类,而在AOP中,模块化单元是方面. 准备工作 首先,使用AOP要在build.gradle中加入依赖 //引入AOP依赖 compile "org.springframework.boot:spring-boot-starter-aop:${springBootVersion}" 然后在application.yml中

一篇文章带你搞懂spring全家桶套餐

spring全家桶里都有哪些食物 上期我们讲了spring和springmvc两个框架的基础知识和学习路线,而这期内容,我们将围绕着spring全家桶展开来讨论. 大家应该都知道,按照出现的顺序,spring全家桶大概包含了spring.springmvc.springboot以及springcloud,从开胃小菜spring到满汉全席springcloud,spring全家桶可谓Java工程师的必备大餐,那么,我们不妨先来看看,spring全家桶是如何从光杆司令spring发展到如今的庞大家族

玩转Spring全家桶

庸置疑,Spring 早已成为 Java 后端开发事实上的行业标准,无数的公司选择 Spring 作为基础的开发框架,大部分 Java 后端程序员在日常工作中也会接触到 Spring ,因此,如何用好 Spring ,也就成为 Java 程序员的必修课之一. 同时,Spring Boot 和 Spring Cloud 的出现,可以帮助工程师更好地基于 Spring 及各种基础设施来快速搭建系统,可以说,它们的诞生又一次解放了大家的生产力. 因此,Spring Boot 和 Spring Clou

Spring全家桶系列--SpringBoot与Mybatis结合

Mybatis 是一个持久层ORM框架,负责Java与数据库数据交互,也可以简易理解为中介,相对于它,还有个中介是hibernate,不过在mybatis中sql语句的灵活性,可优化性比较强,这也是现在大多数人选择的原因. mapper.xml.dao接口.实体类自动生成 下载 :https://pan.baidu.com/s/1JY7Xduk5E3KPm58AjnueuQ 工具包 1.1 修改配置文件generator.xml 解压之后,这里把文件拷贝到了C:\resources\genera

如何掌握 Spring,Spring Boot 全家桶?系统学习 Spring 的大纲一份(实战教学)

搞个推荐! 资深的 Spring 工程师应该都知道 Spring 界的大牛丁雪丰.作为平安壹钱包的高级架构师之余,他不仅翻译了<Spring Boot 实战><Spring 攻略>两本书,还出了一门一揽子解决 Spring 全家桶的课程<玩转 Spring 全家桶>. 他在推荐自己的这门课程时说, 市面上有很多书和教程,但对于很多开发人员,在学习 Spring 的时候,难免会遇到这些问题: 官方文档虽然全面,但面对庞杂的知识体系,很多初学者一时不知该从哪里下手: 手册式

【Spring Cloud】全家桶介绍(一)

摘自:https://www.cnblogs.com/iUtopia/p/11492072.html 一.微服务架构# 1.微服务架构简介# 1.1.分布式:不同的功能模块部署在不同的服务器上,减轻网站高并发带来的压力. 1.2.集群:多台服务器上部署相同应用构成一个集群,通过负载均衡共同向外提供服务. 1.3.微服务:微服务架构模式就是将web应用拆分为一系列小的服务模块,这些模块可以独立地编译.部署,并通过各自暴露的API接口通讯,共同组成一个web应用. 1.4.SpringCloud是基