栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Day93.SpringBoot: 配置、使用、原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Day93.SpringBoot: 配置、使用、原理

目录

一、SpringBoot概述

二、使用springboot

二、配置文件详解

1. 属性配置文件

2. YAML配置文件 

3. 多环境profile切换配置

三、Spring Boot自动配置(理解)

条件化配置注解

四、自动配置原理

默认属性配置

五、自定义启动器 

六、Spring Data JPA

Spring Boot综合案例(应用)

1、环境搭建 (数据库、结构)

2、数据访问层

3、Service 业务层

4、Controller 表现层


一、SpringBoot概述

Spring Boot是Spring项目中的一个子工程,与我们所熟知的Spring-framework 同属于spring的产品。其最主要作用就是帮助开发人员快速的构建庞大的spring项目,并且尽可能的减少一切xml配置,做到开箱即用,迅速上手,让开发人员关注业务而非配置。
设计目的: 用来简化 Spring 应用的初始搭建以及开发过程。

(1)为所有 Spring 开发提供一个更快更广泛的入门体验。

(2)零配置。无冗余代码生成和XML 强制配置,遵循“约定大于配置,习惯优于配置” 。

(3)集成了大量常用的第三方库的配置, Spring Boot 应用为这些第三方库提供了几乎可以零配置的开箱即用的能力。

(4)提供一系列大型项目常用的非功能性特征,如嵌入服务器等。

主要特点:

  1. 自动配置 : 不需要再关注各个框架的整合配置, springboot全部已经配置好了
  2. 起步依赖 : 我们在需要使用某个框架的时候, 直接添加这个框架的启动器依赖即可 , 不需要在关注jar包的冲突和整合

二、使用springboot

1. pom.xml 添加父工程坐标、web启动器



    4.0.0

    com.atguigu
    springboot_01
    1.0
    
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.6.RELEASE
    
    
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
    
    
    
        1.8
    

2. 创建启动类

Spring Boot项目通过main函数即可启动,我们需要创建一个启动类:

@SpringBootApplication //s声明当前项目是一个SpringBoot项目
public class App {
    //启动内置的Tomcat服务器,即初始化Ioc容器(采用框架默认配置)
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

3. 编写Controller

@RestController //相当于 @Controller + @ResponseBody
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello(){
        return "hello spring boot!!" ;
    }
}

4. 启动测试

 

5. 问题

1、为什么我们在添加启动器的时候不需要在启动器的坐标中指定版本?

答案:因为我们指定了项目的父工程,在spring-boot-starter-parent中已经通过Maven的版本锁定了Jar包的版本,所以就不需要再指定了。

2、为什么我们就添加一个启动器依赖,项目就可以运行起来了,运行项目所需要的Jar包从何而来?

答案:因为我们添加了这个启动器的依赖,它已经把自己运行所需要的必要包集成在这个启动器中,通过Maven的依赖传递性,将这些包都依赖到咱们的项目里了。

二、配置文件详解

springboot支持二种类型的配置文件

  • properties属性配置文件
  • yaml配置文件

配置文件必须放置在项目的类加载目录下, 并且名字必须是 application,springboot项目在运行的时候会自动加载这些配置文件

1. 属性配置文件

spring.jdbc.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.jdbc.datasource.url=jdbc:mysql://localhost:3306/db_house?characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
spring.jdbc.datasource.username=root
spring.jdbc.datasource.password=******

 新建 properties 包,创建类 DataSourceProperties 

package com.atguigu.properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DataSourceProperties {

    // @Value 可以获取属性配置文件的属性值,无需get/set方法。缺点:需要一个一个获取
    @Value("${spring.jdbc.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.jdbc.datasource.url}")
    private String url;
    @Value("${spring.jdbc.datasource.username}")
    private String username;
    @Value("${spring.jdbc.datasource.password}")
    private String password;

    // 生成get set 和 toString方法
}

测试:

 成功注入

2. YAML配置文件 

YAML是一种配置文件格式,扩展名是 yaml 或 yml

1.数据结构用树形结构呈现,通过缩进来表示层级,

2.连续的项目通过减号 ” - ” 来表示

3.键值结构里面的key/value对用冒号 ” : ” 来分隔。

 spring:

  jdbc:

    datasource:

      driverClassName: com.mysql.jdbc.Driver

      url: jdbc:mysql:///springboot_01

      username: root

      password: root

yml配置文件的特征:

  1. 树状层级结构展示配置项;
  2. 配置项之间如果有关系的话需要分行,空两格;
  3. 配置项如果有值的话,那么需要在 :之后空一格再写配置项值;

3. 多环境profile切换配置

在Spring Boot项目中配置文件的名称只能是**application** , 如果我们把所有的配置项全都写在一个配置文件中, 配置文件就会比较复杂和臃肿,不利于后期的项目维护和开发。

1.因为开发环境的变化, 我们需要修改配置文件中某一个配置项的值(比如之前是mysql数据库,切换成oracle数据库)

2.项目开发完成需要上线了 , 需要把一些环境修改成正式环境(开发,测试,上线,多环境切换)

解决方案 :使用profiles拆分配置

spring boot项目中允许使用多个YAML配置文件。

这些文件名称必须为application-***.yml,并且在application.yml中激活。

spring:
  profiles:
    active: dev

 注意 :

如果properties和yml文件都存在,不存在spring.profiles.active设置,如果有重叠属性,默认以properties优先。

如果设置了spring.profiles.active,并且有重叠属性,以active设置优先。

可以在两种文件中分别增加server.port属性指定不同的端口,启动项目查看控制台端口号进行测试。

三、Spring Boot自动配置(理解)

@SpringBootApplication 注解

  • @SpringBootConfiguration : 代表这个类就是一个配置类 , 本质上就是一个@Configuration注解
  • @EnableAutoConfiguration : 自动配置注解 , 添加了此注解会自动去读取spring.factories配置文件中的自动配置类
  • @ComponentScan : 组件扫描, 默认扫描启动类所在包及子包下的类身上的注解

@ConfigurationProperties(prefix = "xxx") 注解

  • @ConfigurationProperties是SpringBoot提供的重要注解, 他可以将一些配置属性批量注入到bean对象(需要提供get set方法)。(@Value 注解需要属性需要一个一个获取)

报错提示,请在pom文件添加配置信息即可(不影响运行)


    org.springframework.boot
    spring-boot-configuration-processor
    true

@Value 一个个注入 

    // @Value 可以获取属性配置文件的属性值,无需get/set方法。缺点:需要一个一个获取
    @Value("${spring.jdbc.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.jdbc.datasource.url}")
    private String url;
    @Value("${spring.jdbc.datasource.username}")
    private String username;
    @Value("${spring.jdbc.datasource.password}")
    private String password;

条件化配置注解

注解

作用

@ConditionalOnBean

如果存在某个Bean, 配置类生效

@ConditionalOnMissingBean

如果不存在某个Bean, 配置类生效

@ConditionalOnClass

如果存在某个类, 配置类生效

@ConditionalOnMissingClass

如果不存在某个类, 配置类生效

@ConditionalOnProperty

如果存在某个属性配置, 配置类生效

@ConditionalOnWebApplication

如果是一个web应用, 配置类生效

@ConditionalOnNotWebApplication

如果不是一个web应用, 配置类生效

@RestController //相当于 @Controller + @ResponseBody
//启用属性配置类,带@ConfigurationProperties属性的类要先生效
@EnableConfigurationProperties(value = {DataSourceProperties.class})
public class HelloController {

    @Autowired
    DataSourceProperties dataSourceProperties;

    @RequestMapping("/hello")
    public String sayHello(){
        System.out.println(dataSourceProperties);

        return "hello spring boot!!" ;
    }
}

四、自动配置原理
@SpringBootApplication //声明当前项目是一个SpringBoot项目
public class App {
    //启动内置的Tomcat服务器,即初始化Ioc容器(采用框架默认配置)
    public static void main(String[] args) {

        SpringApplication.run(App.class,args);
    }
}

彩蛋 :英姿飒爽的张宇老师

 

 在SpringApplication类构建的时候,有这样一段初始化代码:

 跟进去往下走

 这里发现会通过loadFactoryNames尝试加载一些FactoryName,然后利用createSpringFactoriesInstances将这些加载到的类名进行实例化。 继续跟进loadFactoryNames方法: 发现此处会利用类加载器加载一个文件: META-INF/spring.factories 。我们知道,ClassLoader默认是从classpath下读取文件,因此,SpringBoot会在初始化的时候,加载所有classpath:META-INF/spring.factories文件,包括jar包当中的。而在Spring的一个依赖包:spring-boot-autoconfigure中,就有这样的文件:

我们引入的任何第三方启动器,只要实现自动配置,也都会有类似文件。

打开后,可以发现以EnableAutoConfiguration接口为key的一系列配置,key所对应的值,就是所有的自动配置类,可以在当前的jar包中找到这些自动配置类,几乎涵盖了现在主流的开源框架

默认属性配置

配置类我们找到了 , 那么这些默认配置的属性来自哪里呢?

例如 : 我们配置视图解析器的时候需要配置前缀和后缀 , 那么这些配置在哪配置的呢 ?

通过源码发现, 这个配置是从this.mvcProperties.getView()中读取的 ,this.mvcProperties又是什么呢 ? 我们继续跟踪,发现其实就是定义的一个变量

 这个变量中又有一个View类型的变量 , 这个变量中配置的就是前缀和后缀,默认为null  

五、自定义启动器 

定义一个连接池启动器 , 当用户引入了连接池启动依赖之后 , 项目中就已经自动配置了连接池

1、开发启动器。2、使用启动器

六、Spring Data JPA

JPA 底层是 hibernate

1. 添加Spring Data JPA的起步依赖

    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.6.RELEASE
        
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
        
            mysql
            mysql-connector-java
        

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

    

2. 在application.yml中配置数据库和jpa的相关属性

logging:
  level:
    com.atguigu.dao: debug # 配置日志
spring:
  datasource:
    username: root
    password: *******
    url: jdbc:mysql://127.0.0.1:3306/springboot?characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    database: mysql
    show-sql: true
    generate-ddl: true
    hibernate:
      # update : 表不存在会自动创建表; 表存在,类与表一致,无需任何操作。类与表不一致,更新表结构
      ddl-auto: update
      naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
server:
  port: 18081

3. 创建实体配置实体

package com.atguigu.daomain;

import javax.persistence.*;



@Entity  //声明实体类
@Table(name = "t_user") //推荐使用JPA提供的注解,声明表
public class User implements Serializable {

    @Id //当前属性为主键
    //设置主键生成方式: auto_increment 由数据库生成
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id",unique = false) //字段名,长度,不为空 字段的约束
    private Long id;

    @Column(name = "username",length = 8)
    private String username;

    @Column(name = "password",length = 8)
    private String password;

    //@Column(name = "name",length = 8)
    //如果不指定@Column注解,框架会自动映射
    private String name;

    public User() {}
    public User(String username, String password, String name) {
        this.username = username;
        this.password = password;
        this.name = name;
    }

    //get、set、tostring
}

4. Dao层,只需要继承父接口 JpaRepository

package com.atguigu.dao;

import com.atguigu.daomain.User;
import org.springframework.data.jpa.repository.JpaRepository;

//只需要继承父接口,父接口中提供了CRUD操作,自己无需声明这些方法
//无需自定义映射配置文件了,特殊情况除外
public interface UserDao extends JpaRepository {

}

5. Service层

public interface UserService {
    List findUsers();
    User findUserById(Long id);
    void saveUser(User user);
    void updateUser(User user);
    void deleteUserById(Long id);
}


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public List findUsers() {
        return userDao.findAll();
    }

    @Override
    public User findUserById(Long id) {
        return userDao.findById(id).get();//注意,需要
    }

    @Override
    public void saveUser(User user) {
        //user对象主键值为null,进行保存操作
        userDao.save(user);
    }

    @Override
    public void updateUser(User user) {
        //user对象含有主键值,进行更新操作
        userDao.save(user); //一个方法多用
    }

    @Override
    public void deleteUserById(Long id) {
        userDao.deleteById(id);
    }
}

6. Controller层

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findAll")
    public List findAll(){
        System.out.println("findAll()执行了");
        return userService.findUsers();
    }

    @RequestMapping("/saveUser")
    public void saveUser(){
        User user = new User("张三", "123456", "zs");
        userService.saveUser(user);
        System.out.println("保存成功");
    }
}

7. 编写主程序类 App

@SpringBootApplication
public class App {

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

}

启动后,表不存在会自动构建 (注意端口配置为18081)

 

七、Spring Boot综合案例 (应用 通用Mappe)

通用Mapper?

1、环境搭建 (数据库、结构)

1. 数据库建表

create database springboot character set utf8 ;

use springboot ; 

CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `gender` varchar(5) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(32) DEFAULT NULL,
  `qq` varchar(20) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `username` varchar(20) NOT NULL,
  `phone` varchar(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_username_uindex` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

INSERT INTO `tb_user` VALUES (1,'黄蓉','女',38,'桃花岛','212223390222','huangrong222@qq.com','huangrong','15600003333'),(2,'黄老邪','男',58,'湖北省武汉市','212223390','huanglaoxie@qq.com','huanglaoxie','15872320405'),(3,'小龙女','男',18,'湖北省荆门市','212223390','xiaolongnv@qq.com','xiaolongnv','15600004444'),(7,'杨过','男',30,'扬州','212223390','yangguo@qq.com','yangguo','15600005555');

2. 项目依赖 



    4.0.0

    com.atguigu
    springboot_04_case
    1.0

    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.6.RELEASE
    

    
        
        
            org.springframework.boot
            spring-boot-starter-test
        

        
        
            tk.mybatis
            mapper-spring-boot-starter
            2.1.5
        
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
        
            mysql
            mysql-connector-java
            8.0.26
        
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        

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

        
        
            org.apache.commons
            commons-lang3
        

        
        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
    

    
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
                
            
        
    

3. 创建启动类

package com.atguigu;



import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;


@SpringBootApplication
//注意导包!! 采用通用mapper框架提供的注解 tk.mybatis
@MapperScan(basePackages = "com.atguigu.dao")
@EnableTransactionManagement //开启声明式事务
public class App {

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

}

2、数据访问层

1. 编写配置文件application.yml

server:
  port: 10001
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot?characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    username: root
    password: *******
    type: com.alibaba.druid.pool.DruidDataSource

#类型别名包
mybatis:
  type-aliases-package: com.atguigu.pojo

 2. 实体类

@Entity
@Table(name = "tb_user")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String gender;
    private Integer age;
    private String address;
    private String qq;
    private String email;
    private String username;
    private String phone;

    //get、set、tostring
}

3. Mapper接口和映射配置 (继承通用Mapper框架接口)

package com.atguigu.dao;

import com.atguigu.pojo.User;
import tk.mybatis.mapper.common.Mapper;

//继承通用Mapper框架提供的Mapper接口 注:与jpa不同
//通用Mapper框架,在MyBatis 基础上进行分装,可以动态生成SEL语句,封装了CRUD
public interface UserMapper extends Mapper {
}

4. 测试

@RunWith(SpringRunner.class) //指定Junit核心运行类
//xml文件的方式
//@ContextConfiguration(locations = "classpath:/spring/spring-*/xml")
@SpringBootTest //springboot配置类方式 指定这是一个Spring Boot的测试类, 运行时会自动加载Spring Boot运行环境
public class UserMapperTest {

    @Autowired
    UserMapper userMapper;

    @Test
    public void testFindAll(){
        List list = userMapper.selectAll();;
        for (User user : list) {
            System.out.println(user);
        }
    }
}

3、Service 业务层

1. 接口、实现类

public interface UserService {
    public List findAll();
}

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)
    public List findAll() {
        return userMapper.selectAll();
    }
}

4、Controller 表现层

1. 检查web起步依赖



    org.springframework.boot
    spring-boot-starter-web




    org.apache.commons
    commons-lang3

2. Controller 代码

@Controller
@RequestMapping(path = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    //查询所有用户信息
    @RequestMapping(path = "/findAll")
    @ResponseBody
    public Result findAll() {
        List users = userService.findAll();
        return Result.ok(users);
    }
}

3. 封装Vo类 Result工具类

package com.atguigu.pojo.vo;

import java.io.Serializable;

public class Result implements Serializable {
    private boolean status ; //响应状态  true  false
    private String msg ;  // 响应信息
    private Object data ;  //处理成功的响应数据

    public static Result ok(Object data){
        Result result = new Result();
        result.setStatus(true);
        result.setData(data);
        return  result ;
    }

    public static Result error(String msg){
        Result result = new Result();
        result.setStatus(false);
        result.setMsg(msg);
        return  result ;
    }
    
    // 生成set get tostring方法
}

5. 测试、页面展示:(文件略 ajax异步请求获取数据) 

6. Redis 缓存优化 

1. 引入起步依赖 redis启动器



    org.springframework.boot
    spring-boot-starter-data-redis

2. 改写配置文件

server:
  port: 10001
spring:
    ....
  redis: # 配置redis
    host: 192.168.86.86
    port: 6379

3. 修改业务层实现类代码

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //通过自动配置产生的
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    @Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)
    public List findAll() {
        List list = (List) redisTemplate.boundValueOps("userList").get();
        if(list!=null && list.size()>0){
            System.out.println("从redis缓存中获取list");
        }else {
            list = userMapper.selectAll();
            redisTemplate.boundValueOps("userList").set(list);
            System.out.println("从数据库中获取list");
        }
        return list;
    }
}

4. 解决乱码问题?(可选)

将一个java对象中的数据放入到redis缓存中,虽然可以正产读写,但是redis查看却是乱码

这是由于序列化数据的编码不一样,需要改变的就是改变RedisTemplate类的默认序列化格式。

 写一个redis的配置类将要加载新的序列化放入到RedisTemplate属性中 config/MyRedis 

@Configuration
//解决乱码序列化数据的编码,改变RedisTemplate类的默认序列化格式、
public class MyRedis {
    @Bean
    public RedisTemplate MyRedisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
      	// 设置其他的k-v的默认的序列化
        template.setDefaultSerializer(new Jackson2JsonRedisSerializer(Object.class));
        //单独设置k的序列化
        template.setKeySerializer(new StringRedisSerializer());
      
        return template;
    }
}
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //通过自动配置产生的 操作k-v都是对象的
    @Autowired
    RedisTemplate redisTemplate;

    //redis配置类中配置的类
    @Autowired
    private RedisTemplate MyRedisTemplate;


    @Override
    @Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)
    public List findAll() {
        List list = (List) MyRedisTemplate.opsForValue().get("userList");
        //List list = (List) redisTemplate.boundValueOps("userList").get();
        if(list!=null && list.size()>0){
            System.out.println("从redis缓存中获取list");
        }else {
            list = userMapper.selectAll();
            // redis配置类中配置的类
            ValueOperations valueOperations = MyRedisTemplate.opsForValue();
            valueOperations.set("userList", list);

            //redisTemplate.boundValueOps("userList").set(list);
            System.out.println("从数据库中获取list");
        }
        return list;
    }
}

八、Spring Boot其他组件 (了解)

1、SpringBoot Actuator组件  健康监控

Spring Boot Actuator是SpringBoot自带的一个组件 , 可以帮助我们监控和管理Spring Boot应用,比如健康检查、审计、统计和HTTP追踪等。

1. 引入SpringBoot Actuator起步依赖



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

2. 配置SpringBoot Actuator参数 

spring:
  ...

#健康监测 monitor/health(beans)(mappings)
management:
    endpoints:
      web:
        exposure:
          include: '*'  # 对外暴露的访问入口 , 默认是/health和/info
        base-path: /monitor # 默认是actuator
    endpoint:
      health:
        show-details: ALWAYS    # 显示所有健康状态
    server:
      port: 9999

3. 常用的访问路径 : 

HTTP 方法

路径

描述

GET

/autoconfig

提供了一份自动配置报告,记录哪些自动配置条件通过了,哪些没通过

GET

/configprops

描述配置属性(包含默认值)如何注入Bean

GET

/beans

描述应用程序上下文里全部的Bean,以及它们的关系

GET

/dump

获取线程活动的快照

GET

/env

获取全部环境属性

GET

/env/{name}

根据名称获取特定的环境属性值

GET

/health

报告应用程序的健康指标,这些值由HealthIndicator的实现类提供

GET

/info

获取应用程序的定制信息,这些信息由info打头的属性提供

GET

/mappings

描述全部的URI路径,以及它们和控制器(包含Actuator端点)的映射关系

GET

/metrics

报告各种应用程序度量信息,比如内存用量和HTTP请求计数

GET

/metrics/{name}

报告指定名称的应用程序度量值

POST

/shutdown

关闭应用程序,要求endpoints.shutdown.enabled设置为true

GET

/trace

提供基本的HTTP请求跟踪信息(时间戳、HTTP头等)

4. 启动项目获取系统信息

2、SpringBoot Admin组件 图形化界面

上面我们讲了Spring Boot Actuator , 可以通过http协议获取系统状态信息 , 但是返回的是JSON格式数据, 看起来不太方便, 而且还需要记忆路径, 比较麻烦 , Spring Boot Admin给我们提供了更加友好的可视化界面来查看这些信息!

Spring Boot Admin是一个开源社区项目,用于管理和监控SpringBoot应用程序。 应用程序作为Spring Boot Admin Client向Spring Boot Admin Server注册 , Client会定时向Server发送数据, Server使用友好的界面展示数据。

图形化

1、创建项目springboot-admin-server

1. 导入依赖

    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.6.RELEASE
    

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            de.codecentric
            spring-boot-admin-starter-server
            2.2.0
        
    

2. 配置application.yml

spring:
  application:
    name: admin-server
server:
  port: 8769 #服务端的端口号

3. 启动类

//健康监控 服务端 SpringBoot Admin组件 健康监控图形化界面
@SpringBootApplication
@EnableAdminServer //开启管理服务
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }
}
2. SpringBoot Admin 客户端

客户端使用之前的项目即可

1. 添加依赖



    de.codecentric
    spring-boot-admin-starter-client
    2.2.0

2. 配置application.yml

注册地址一定要和Spring Boot Admin Server地址匹配

spring:
  ...
  # SpringBoot Admin组件 图形化界面
  application:
    name: admin-client #应用名称
  boot:
    admin:
      client:
        url: http://localhost:8769   # 指定注册地址 , Spring Boot Admin Server地址

3. 启动,访问端口8769进行测试

九、Spring Boot项目打包部署(应用)

1. 项目打包

在pom.xml中配置Spring Boot项目的maven插件


    
        
        
        
            org.springframework.boot
            spring-boot-maven-plugin
            
        
    

打开cmd 运行打出来的包;使用命令:java –jar 包全名  (关闭idea中项目,避免端口冲突)

 成功

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000161.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号