• 博客园 图灵学院spring boot学习2--集成swaagger


     这是项目的代码,在pom.xml依赖中需要引入swagger的依赖

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
    </dependency>

    整个pom.xml文件如下

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.tuling.springboot</groupId>
        <artifactId>vip-springboot-first</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>vip-springboot-first</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.10.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
            
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>

    2.创建Swagger2配置类,

    spring boot启动类所在包或子包中创建Swagger配置类SwaggerConfig.java,如果不再启动类包或者子包下面,一定要使用@ComponentScan(basePackages={"com.example.boot"}) 包扫描扫描到该配置类如下:

    package com.tuling.springboot;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.tuling.springboot"))// 指定扫描包下面的注解
                    .paths(PathSelectors.any())
                    .build();
        }
        // 创建api的基本信息
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("集成Swagger2构建RESTful APIs")
                    .description("集成Swagger2构建RESTful APIs")
                    .termsOfServiceUrl("https://www.baidu.com")
                    .contact("zhangsan")
                    .version("1.0.0")
                    .build();
        }
    }

    这里配置 .apis(RequestHandlerSelectors.basePackage("com.tuling.springboot"))// 指定扫描包下面的注解 swagger扫描的包

    3.创建Controller: SwaggerController.java

    package com.tuling.springboot;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiOperation;
    
    @RestController
    @RequestMapping(value="/swagger")
    public class SwaggerController {
        @ApiOperation(value="获取用户信息", notes="根据id来获取用户详细信息")
        @ApiImplicitParam(name="id", value="用户ID", required=true, dataType="String")
        @RequestMapping(value="/{id}", method=RequestMethod.GET)
        public Map<String,String> getInfo(@PathVariable String id) {
          Map<String ,String> map = new HashMap<String, String>();
          map.put("name", "张三");
          map.put("age", "34");
            return map;
        }
    }

    4.启动Spring boot,访问Swagger UI界面:http://localhost:8081/swagger-ui.html
    5.测试API:

    springboot集成mybatis

    1.修改pom.xml,增加依赖
    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version><!-- 版本号必须需要 -->
    </dependency>
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    </dependency>

    整个工程的pom依赖如下所示

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.tuling.springboot</groupId>
        <artifactId>vip-springboot-first</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>vip-springboot-first</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.10.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
            
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version><!-- 版本号必须需要 -->
    </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
            
            
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>

    2.mysql的连接配置2.mysql的连接配置

    3.创建表t_user
    CREATE TABLE `t_user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(40) DEFAULT NULL,
      `age` int(11) DEFAULT NULL,
      `address` varchar(100) DEFAULT NULL,
      `phone` varchar(40) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

    在application.properties配置数据库的连接

    server.port=8081
    spring.datasource.url=jdbc:mysql://localhost:3306/spring
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver

    4.创建User.java文件

    package com.tuling.springboot;
    public class User {
        private Integer id;
        private String name;
        private Integer age;
        private String address;
        private String phone;
        // getter,setter省略
    }

    5.创建UserMapper.java接口文件,这里我们采用注解的形式

    package com.tuling.springboot;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    @Mapper
    public interface UserMapper {
    /**根据id查询用户*/
    @Select("SELECT * FROM T_USER WHERE ID = #{id}")
        User findById(@Param("id") String id);
    /**新增用户*/
        @Insert("INSERT INTO T_USER(NAME, AGE, ADDRESS, PHONE) VALUES(#{name}, #{age}, #{address}, #{phone})")
        int insert(@Param("name") String name, @Param("age") Integer age,@Param("address") String address,@Param("phone") String phone);
    }

    启动类的代码如下

    package com.tuling.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class VipSpringbootFirstApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(VipSpringbootFirstApplication.class, args);
        }
    }

    这里有个最关键需要注意的地方:UserMapper.java这个类中的@Mapper注解在启动的时候要被springboot扫描到,所以UserMapper.java这个类要位于启动类的包或者子包目录下

    接下来,我们创建一个测试类,对上面的代码进行测试

    package com.tuling.springboot;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import junit.framework.TestCase;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = VipSpringbootFirstApplication.class)
    public class MybatisTest {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testInsert() throws Exception {
    int num = userMapper.insert("zhangsan", 20,"长沙","13100000000");
    TestCase.assertEquals(num,1);
    }
    @Test
    public void testFindById() throws Exception {
    User u = userMapper.findById(14+"");
    TestCase.assertNotNull(u);
    System.out.println(u.getName());
    }
    }

     这里classes要写成对于的启动类

    springboot集成redis组件

    这里我们下载windows版本的redis进行测试

     启动redis使用下面的命令

    3.启动redis
    windows:
    redis-server redis.windows.conf

    集成Redis集成步骤:
    1.修改pom.xml,增加依赖
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    整个pom文件如下

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.tuling.springboot</groupId>
        <artifactId>vip-springboot-first</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>vip-springboot-first</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.10.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.2.2</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.2.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.1.1</version><!-- 版本号必须需要 -->
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>

    接下来进行redis的配置

    server.port=8081
    spring.datasource.url=jdbc:mysql://localhost:3306/spring
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    
    # REDIS (RedisProperties)
    # Redisu6570u636Eu5E93u7D22u5F15uFF08u9ED8u8BA4u4E3A0uFF09
    spring.redis.database=0
    # Redisu670Du52A1u5668u5730u5740
    spring.redis.host=127.0.0.1
    # Redisu670Du52A1u5668u8FDEu63A5u7AEFu53E3
    spring.redis.port=6379
    # Redisu670Du52A1u5668u8FDEu63A5u5BC6u7801uFF08u9ED8u8BA4u4E3Au7A7AuFF09
    spring.redis.password=
    # u8FDEu63A5u6C60u6700u5927u8FDEu63A5u6570uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
    spring.redis.pool.max-active=8
    # u8FDEu63A5u6C60u6700u5927u963Bu585Eu7B49u5F85u65F6u95F4uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
    spring.redis.pool.max-wait=-1
    # u8FDEu63A5u6C60u4E2Du7684u6700u5927u7A7Au95F2u8FDEu63A5
    spring.redis.pool.max-idle=8
    # u8FDEu63A5u6C60u4E2Du7684u6700u5C0Fu7A7Au95F2u8FDEu63A5
    spring.redis.pool.min-idle=0
    # u8FDEu63A5u8D85u65F6u65F6u95F4uFF08u6BEBu79D2uFF09
    spring.redis.timeout=0

    注意:spring.redis.database的配置通常使用0即可,Redis在配置的时候可以设置数据库数量,默认为16,可以理解为数据库的schema

    4.测试

    package com.tuling.springboot;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import junit.framework.TestCase;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = VipSpringbootFirstApplication.class)
    public class SpringRedisTest {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Test
    public void testRedis() throws Exception {
    ValueOperations<String, String> ops = redisTemplate.opsForValue();
    ops.set("name", "zhangsan");
    String value = ops.get("name");
    System.out.println(value);
    TestCase.assertEquals("zhangsan", value);
        }
    }

     注意:redis中存储对象,需要我们自己实现RedisSerializer<T>接口来对传入对象进行序列化和反序列化

    springboot集成rabbitmq组件

    首先在windows上面安装rabbitmq组件

    1.安装RabbitMQ[windows]
    Erlang/OTP 20.3下载地址:
    http://erlang.org/download/otp_win64_20.3.exe
    Erlang/OTP其它版本下载地址:http://www.erlang.org/downloads
    
    RabbitMQ Server 3.7.4下载地址:
    https://dl.bintray.com/rabbitmq/all/rabbitmq-server/3.7.4/rabbitmq-server-3.7.4.exe 
    RabbitMQ其它版本下载地址:https://www.rabbitmq.com/download.html
    
    关于Linux平台怎么安装,同学们自行百度即可

    2.启动RabbitMQ Server
    RabbitMQ Server安装之后,会自动注册为windows服务,并以默认配置启动起来

    3.RabbitMQ管理页面
    1.开启Web管理插件
    进入rabbitmq安装目录的sbin目录,在此打开dos命令窗口,执行以下命令
    rabbitmq-plugins enable rabbitmq_management

    执行这个配置之前需要先在电脑的系统环境变量中添加Erlang的环境变量设置

     

     出现上面说明插件安装成功了

    然后重新启动RabbitMQ 服务,打开浏览器并访问:http://localhost:15672/,并使用默认用户guest登录,密码也为guest,即可进入管理界面

    4.Spring Boot整合
    1.修改pom.xml,增加依赖支持
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    2.新增管理用户并设置权限

     注意tags一定要勾选正确

    username:springboot

    password:123456

     

    2.切换到springboot用户登陆,在All users中,点击Name为springboot, 进入权限设置页面

    3.在权限设置页面,进入Permissions页面,点击“Set permission"

    3.rabbit mq连接配置

    ## rabbitmq config

    spring.rabbitmq.host=localhost

    spring.rabbitmq.port=5672

    spring.rabbitmq.username=springboot

    spring.rabbitmq.password=123456

     

     

    4.创建Rabbit配置类

    配置类主要用来配置队列、交换器、路由等高级信息

    import org.springframework.amqp.core.Queue;

    import org.springframework.context.annotation.Bean;

    import org.springframework.context.annotation.Configuration;

    @Configuration

    public class RabbitConfig {

        @Bean

        public Queue firstQueue() {

          // 创建一个队列,名称为:first

            return new Queue("first");

        }

    }

     

    5.创建消息产生者类

    @Component

    public class Sender {

        @Autowired

        private AmqpTemplate rabbitTemplate;

        public void send() {

            rabbitTemplate.convertAndSend("first", "test rabbitmq message !!!");

        }

    }

     

    说明:通过注入AmqpTemplate接口的实例来实现消息的发送,AmqpTemplate接口定义了一套针对AMQP协议的基础操作

     

    6.创建消息消费者

    @Component

    @RabbitListener(queues = "first")

    public class Receiver {

        @RabbitHandler

        public void process(String msg) {

            System.out.println("receive msg : " + msg);

        }

    }

     

    说明:

    @RabbitListener注解:定义该类需要监听的队列

    @RabbitHandler注解:指定对消息的处理

     

    6.创建测试类

    @RunWith(SpringJUnit4ClassRunner.class)

    @SpringBootTest(classes = SpringBootMain.class)

    public class RabbitmqTest {

        @Autowired

        private Sender sender;

        @Test

        public void testRabbitmq() throws Exception {

            sender.send();

        }

    }

     

    7.启动主程序:SpringBootMain

    控制台如果出现以下信息,则说明rabbitmq连接成功

    Created new connection: rabbitConnectionFactory#29102d45:0/SimpleConnection@1dcfb5ba [delegate=amqp://springboot@127.0.0.1:5672/, localPort= 55088]

     

    8.运行Junit测试类

    控制台输出:

    receive msg : test rabbitmq message !!!

     

    集成Rabbit MQ完毕!

     

    spring boot 日志框架

    Spring boot 日志日志实现默认使用的logback

    Spring Boot 应用将自动使用 logback 作为应用日志框架, Spring Boot 启动的时候,由 org.springframework.boot.logging.Logging.LoggingApplicationListener 根据情况初始化并使用。
    值得注意的是,默认情况下,Spring Boot 使用 logback 作为应用日志框架。因为 spring-boot-starter 其中包含了 spring-boot-starter-logging,该依赖就是 使用Spring Boot 默认的日志框架 logback,所以不用再

    添加logback的依赖

    【程序中使用】:
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    private final Logger logger = LoggerFactory.getLogger(SampleController.class);

    默认情况下,Spring Boot 配置的是INFO 日志级别,也就是会输出INFO级别以上的日志( ERROR, WARN, INFO )。如果需要 Debug 级别的日志。在 src/main/resources/application.properties 中配置。
    debug=true
    此外,配置 logging.level.* 来具体输出哪些包的日志级别。
    例如
    logging.level.root=INFO
    logging.level.org.springframework.web=DEBUG
    logging.level.com.example.boot.controller=DEBUG

    日志文件

    默认情况下, Spring Boot 日志只会输出到控制台,并不会写入到日志文件,因此,对于正式环境的应用,我们需要通过在 application.properites 文件中配置 logging.file 文件名称和 logging.path 文件路径,将日志输出到日志文件中。

    logging.path = /var/tmp

    logging.file = xxx.log

    logging.level.root = info

    如果只配置 logging.path,在 /var/tmp文件夹生成一个日志文件为 spring.log。如果只配置 logging.file,会在项目的当前路径下生成一个 xxx.log 日志文件。

    值得注意的是,日志文件会在 10MB 大小的时候被截断,产生新的日志文件。

    常用的日志框架 log4j

    如果,我们希望使用 log4j 或者 log4j2,我们可以采用类似的方式将它们对应的依赖模块加到 Maven 依赖中。

    集成log4j2

    spring-boot-dependencies POMs中搜索spring-boot-starter-log4j2

    发现Spring boot父Pom中自己提供了这个依赖,于是我们加入如下jar依赖:

    <!-- log4j2 -->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter</artifactId>

        <exclusions>

            <exclusion>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-starter-logging</artifactId>

            </exclusion>

        </exclusions>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-log4j2</artifactId>

    </dependency>

     

    日志使用跟上面logback一样。

    集成log4j

    spring-boot-dependencies POMs中搜索spring-boot-starter-log4j

    发现Spring boot的父Poms中自己并没有提供了这个依赖, 我们在http://mvnrepository.com

    中央仓库中查找spring-boot-starter-log4j

    1.加入pom依赖

    <!-- log4j start -->

    <dependency>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-starter</artifactId>

                <exclusions>

                    <exclusion>

                        <groupId>org.springframework.boot</groupId>

                        <artifactId>spring-boot-starter-logging</artifactId>

                    </exclusion>

                </exclusions>

            </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-log4j</artifactId>

        <version>1.3.8.RELEASE</version>

    </dependency>

    <!-- log4j end -->

     

    1. classpath下增加log4j.properties

    log4j.rootCategory=INFO, stdout, file, errorfile

    log4j.category.com.example.boot=INFO, myFile

    log4j.logger.error=errorfile

     

    # 控制台输出

    log4j.appender.stdout=org.apache.log4j.ConsoleAppender

    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

     

    # root日志输出

    log4j.appender.file=org.apache.log4j.DailyRollingFileAppender

    log4j.appender.file.file=logs/all.log

    log4j.appender.file.DatePattern='.'yyyy-MM-dd

    log4j.appender.file.layout=org.apache.log4j.PatternLayout

    log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

     

    # error日志输出

    log4j.appender.errorfile=org.apache.log4j.DailyRollingFileAppender

    log4j.appender.errorfile.file=logs/error.log

    log4j.appender.errorfile.DatePattern='.'yyyy-MM-dd

    log4j.appender.errorfile.Threshold = ERROR

    log4j.appender.errorfile.layout=org.apache.log4j.PatternLayout

    log4j.appender.errorfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

     

    # com.example.boot下的日志输出

    log4j.appender.myFile=org.apache.log4j.DailyRollingFileAppender

    log4j.appender.myFile.file=logs/my.log

    log4j.appender.myFile.DatePattern='.'yyyy-MM-dd

    log4j.appender.myFile.layout=org.apache.log4j.PatternLayout

    log4j.appender.myFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L ---- %m%n

     

    3.代码中使用log4j

    import org.apache.log4j.Logger;

    private final Logger logger = Logger.getLogger(xxx.class);

     

    springboot的启动流程原理

     下一步会调用生成一个springapplication的对象,然后调用改对象的run方法

     我们看如何生成springapplication的对象,会首先调用方法

     initalize的方法如下

     

    启动流程:

    1、创建SpringApplication对象

     

    initialize(sources);
    private void initialize(Object[] sources) {
     
        //保存主配置类
        if (sources != null && sources.length > 0) {
            this.sources.addAll(Arrays.asList(sources));
        }
        //判断当前是否一个web应用
        this.webEnvironment = deduceWebEnvironment();
        //从类路径下找到META-INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起来
        setInitializers((Collection) getSpringFactoriesInstances(
            ApplicationContextInitializer.class));
        //从类路径下找到ETA-INF/spring.factories配置的所有ApplicationListener
        setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        //从多个配置类中找到有main方法的主配置类
        this.mainApplicationClass = deduceMainApplicationClass();
    }

     

     

     

     上面就完成了第一步,成功了创建了一个SpringApplication对象,接下来重点看下调用SpringApplication对象的run方法

        public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
            return new SpringApplication(sources).run(args);
        }

     run方法的代码如下,我们进入断点进行调试

        public ConfigurableApplicationContext run(String... args) {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            ConfigurableApplicationContext context = null;
            FailureAnalyzers analyzers = null;
            configureHeadlessProperty();
            SpringApplicationRunListeners listeners = getRunListeners(args);
            listeners.starting();
            try {
                ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                        args);
                ConfigurableEnvironment environment = prepareEnvironment(listeners,
                        applicationArguments);
                Banner printedBanner = printBanner(environment);
                context = createApplicationContext();
                analyzers = new FailureAnalyzers(context);
                prepareContext(context, environment, listeners, applicationArguments,
                        printedBanner);
                refreshContext(context);
                afterRefresh(context, applicationArguments);
                listeners.finished(context, null);
                stopWatch.stop();
                if (this.logStartupInfo) {
                    new StartupInfoLogger(this.mainApplicationClass)
                            .logStarted(getApplicationLog(), stopWatch);
                }
                return context;
            }
            catch (Throwable ex) {
                handleRunFailure(context, listeners, analyzers, ex);
                throw new IllegalStateException(ex);
            }
        }
    environment的值如下
    StandardServletEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[StubPropertySource {name='servletConfigInitParams'}, StubPropertySource {name='servletContextInitParams'}, MapPropertySource {name='systemProperties'}, SystemEnvironmentPropertySource {name='systemEnvironment'}, RandomValuePropertySource@1068586139 {name='random', properties=java.util.Random@ea6147e}, ConfigurationPropertySources@1292040526 {name='applicationConfigurationProperties', properties=[EnumerableCompositePropertySource@726181440 {name='applicationConfig: [profile=]', properties=[PropertiesPropertySource {name='applicationConfig: [classpath:/application.properties]'}]}]}]}
    public ConfigurableApplicationContext run(String... args) {
       StopWatch stopWatch = new StopWatch();
       stopWatch.start();
       ConfigurableApplicationContext context = null;
       FailureAnalyzers analyzers = null;
       configureHeadlessProperty();
        
       //获取SpringApplicationRunListeners;从类路径下META-INF/spring.factories
       SpringApplicationRunListeners listeners = getRunListeners(args);
        //回调所有的获取SpringApplicationRunListener.starting()方法
       listeners.starting();
       try {
           //封装命令行参数
          ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                args);
          //准备环境
          ConfigurableEnvironment environment = prepareEnvironment(listeners,
                applicationArguments);
                //创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准备完成
           
          Banner printedBanner = printBanner(environment);
           
           //创建ApplicationContext;决定创建web的ioc还是普通的ioc
          context = createApplicationContext();
           //异常报告
          analyzers = new FailureAnalyzers(context);
           //准备上下文环境;将environment保存到ioc中;而且applyInitializers();
           //applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法
           //回调所有的SpringApplicationRunListener的contextPrepared();
           //prepareContext运行完成以后回调所有的 SpringApplicationRunListener的contextLoaded();
          prepareContext(context, environment, listeners, applicationArguments,
                printedBanner);
          
           //s刷新容器;ioc容器初始化(如果是web应用还会创建嵌入式的Tomcat);Spring注解版
           //扫描,创建,加载所有组件的地方;(配置类,组件,自动配置)
          refreshContext(context);
           //从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调
           //ApplicationRunner先回调,CommandLineRunner再回调
          afterRefresh(context, applicationArguments);
     
           //所有的SpringApplicationRunListener回调finished方法
          listeners.finished(context, null);
          stopWatch.stop();
          if (this.logStartupInfo) {
             new StartupInfoLogger(this.mainApplicationClass)
                   .logStarted(getApplicationLog(), stopWatch);
          }
           //整个SpringBoot应用启动完成以后返回启动的ioc容器;
          return context;
       }
       catch (Throwable ex) {
          handleRunFailure(context, listeners, analyzers, ex);
          throw new IllegalStateException(ex);
       }
    }

    //获取SpringApplicationRunListeners;从类路径下META-INF/spring.factories

    //准备上下文环境;将environment保存到ioc中;而且applyInitializers();
     //applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法
      //回调所有的SpringApplicationRunListener的contextPrepared();
     //prepareContext运行完成以后回调所有的 SpringApplicationRunListener的contextLoaded();
    private void prepareContext(ConfigurableApplicationContext context,
                ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
                ApplicationArguments applicationArguments, Banner printedBanner) {
            context.setEnvironment(environment);
            postProcessApplicationContext(context);
            applyInitializers(context);
            listeners.contextPrepared(context);
            if (this.logStartupInfo) {
                logStartupInfo(context.getParent() == null);
                logStartupProfileInfo(context);
            }
    
            // Add boot specific singleton beans
            context.getBeanFactory().registerSingleton("springApplicationArguments",
                    applicationArguments);
            if (printedBanner != null) {
                context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
            }
    
            // Load the sources
            Set<Object> sources = getSources();
            Assert.notEmpty(sources, "Sources must not be empty");
            load(context, sources.toArray(new Object[sources.size()]));
            listeners.contextLoaded(context);
        }

     springboot启动配置原理之三(事件监听机制)

     

    package com.tuling.springboot;
    
    import org.springframework.context.ApplicationContextInitializer;
    import org.springframework.context.ConfigurableApplicationContext;
    
    public class HelloApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
    System.out.println("123456 ApplicationContextInitializer...initialize..."+applicationContext);
    }
    }
    package com.tuling.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.SpringApplicationRunListener;
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.core.env.ConfigurableEnvironment;
    
    public class HelloSpringApplicationRunListener implements SpringApplicationRunListener {
    
        //必须有的构造器
        public HelloSpringApplicationRunListener(SpringApplication application, String[] args){
    
        }
    
        @Override
        public void starting() {
            System.out.println("123456 :SpringApplicationRunListener...starting...");
        }
    
        @Override
        public void environmentPrepared(ConfigurableEnvironment environment) {
            Object o = environment.getSystemProperties().get("os.name");
            System.out.println("123456 SpringApplicationRunListener...environmentPrepared.."+o);
        }
    
        @Override
        public void contextPrepared(ConfigurableApplicationContext context) {
            System.out.println("123456 SpringApplicationRunListener...contextPrepared...");
        }
    
        @Override
        public void contextLoaded(ConfigurableApplicationContext context) {
            System.out.println("123456 SpringApplicationRunListener...contextLoaded...");
        }
    
        @Override
        public void finished(ConfigurableApplicationContext context, Throwable exception) {
            System.out.println("123456 SpringApplicationRunListener...finished...");
        }
    }
    对于实现了SpringApplicationRunListener和ApplicationContextInitializer 以上两个起作用,必须配置在resources下META-INF/spring.factories
    org.springframework.context.ApplicationContextInitializer=
    com.tuling.springboot.HelloApplicationContextInitializer
    
    org.springframework.boot.SpringApplicationRunListener=
    com.tuling.springboot.HelloSpringApplicationRunListener
    package com.tuling.springboot;
    
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.stereotype.Component;
    
    //放在ioc容器中即可
    @Component
    public class HelloApplicationRunner implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println("123456 ApplicationRunner...run....");
        }
    }
    package com.tuling.springboot;
    
    import java.util.Arrays;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class HelloCommandLineRunner implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("123456 CommandLineRunner...run..."+ Arrays.asList(args));
        }
    }
    对于实现了CommandLineRunner和ApplicationRunner我们只需要添加到IOC容器中,使用@Component注解,不需要在META-INF/spring.factories中配置
    我们运行程序,我们来看下程序运行的结果打印

     s1:

    //获取SpringApplicationRunListeners;从类路径下META-INF/spring.factories
    s2:
     //回调所有的获取SpringApplicationRunListener.starting()方法
    打印输出123456 :SpringApplicationRunListener...starting...
    S3:
    //创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准备完成
    打印输出:
    123456 SpringApplicationRunListener...environmentPrepared..Windows 7
    s4:

    //准备上下文环境;将environment保存到ioc中;而且applyInitializers();
    //applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法
    //回调所有的SpringApplicationRunListener的contextPrepared();
    //prepareContext运行完成以后回调所有的 SpringApplicationRunListener的contextLoaded();

    打印输出:

    123456 ApplicationContextInitializer...initialize...org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@770c2e6b: startup date [Thu Jan 01 08:00:00 CST 1970]; root of context hierarchy
    123456 SpringApplicationRunListener...contextPrepared...

    123456 SpringApplicationRunListener...contextLoaded...

    s5:

    //从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调
    //ApplicationRunner先回调,CommandLineRunner再回调

    打印输出:

    123456 ApplicationRunner...run....
    123456 CommandLineRunner...run...[]

    s6: //所有的SpringApplicationRunListener回调finished方法

    123456 SpringApplicationRunListener...finished...

     

     springboot自定义starter

     

     我们首先按照自定义命名空间定义一个starer

     整个pom文件的依赖如下

     

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.aitiguigu</groupId>
    <artifactId>springboottest-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    
    


    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    </properties>

    
    

    <dependencies>
    <!--引入自动配置模块-->
    <!--引入spring-boot-starter-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>1.5.10.RELEASE</version>
    </dependency>

    
    

    </dependencies>

    
    

    <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    </plugins>
    </build>

    
    


    </project>

    
    

    创建自己的starter项目
    创建普通maven项目,修改pom.xml,增加自动配置依赖
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>1.5.10.RELEASE</version>
    </dependency>
    我们这个starter并不做其他复杂逻辑的编写,所以这里的依赖只是添加了spring-boot-autoconfigure,实战开发时可以添加任意依赖到项目中。

    接下来我们要在配置文件中配置下面的形式的配置

    springboottest.hello.prefix=sss
    springboottest.hello.suffix=222
    要让springboot能够自动给我们加载如何实现了
    首先把上面的配置文件封装成一个对象
    package com.springboottest.starter;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    //绑定文件中所有以springboottest.hello 开始的配置
    @ConfigurationProperties(prefix = "springboottest.hello")
    public class HelloProperties {
        private String prefix;
        private String suffix;
    
        public String getPrefix() {
            return prefix;
        }
    
        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }
    
        public String getSuffix() {
            return suffix;
        }
    
        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }
    }

    配置映射参数实体
    starter是如何读取application.properties或者application.yml配置文件内需要的配置参数的呢?那么接下来我们就看看如何可以获取自定义的配置信息。
    SpringBoot在处理这种事情上早就已经考虑到了,所以提供了一个注解@ConfigurationProperties,该注解可以完成将application.properties配置文件内的有规则的配置参数映射到实体内的field内,不过需要提供setter方法,自定义配置参数实体代码如下所示:

    这里一定要使用注解@ConfigurationProperties,说明这个是一个属性对于的配置文件类,指定配置文件的属性以springboottest.hello开头
    接下来我们编写一个业务类来操作HelloProperties
    package com.springboottest.starter;
    
    public class HelloService {
       HelloProperties helloProperties;
    
    
        public HelloProperties getHelloProperties() {
            return helloProperties;
        }
    
        public void setHelloProperties(HelloProperties helloProperties) {
            this.helloProperties = helloProperties;
        }
    
        public  String sayHello(String name){
          return  helloProperties.getPrefix()+"-"+ name + helloProperties.getSuffix();
        };
    }
    这里一定要实现HelloProperties对象的getter和setter方法
    接下来我们编写一个配置类HelloServiceAutoConfiguration,把HelloService注入到spring IOC容器 中,然后能够自动扫描@ConfigurationProperties的注解
    我们为自定义starter提供一个Service,并且提供一个名为sayHello的方法用于返回我们配置的msg内容。代码如下所示:
    package com.springboottest.starter;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ConditionalOnWebApplication//web应用才生效
    @EnableConfigurationProperties(HelloProperties.class)//让属性生效 HelloProperties helloProperties;
    public class HelloServiceAutoConfiguration {
    
        //让属性生效 HelloProperties helloProperties;
        @Autowired
        HelloProperties helloProperties;
        @Bean
        public  HelloService helloService(){
            HelloService service = new HelloService();
            service.setHelloProperties(helloProperties);
            return  service;
        }
    
    }

    自动化配置代码中有很多我们之前没有用到的注解配置,我们从上开始讲解
    @Configuration:这个配置就不用多做解释了,我们一直在使用
    @EnableConfigurationProperties:这是一个开启使用配置参数的注解,value值就是我们配置实体参数映射的ClassType,将配置实体作为配置来源。
    SpringBoot内置条件注解
    有关@ConditionalOnXxx相关的注解这里要系统的说下,因为这个是我们配置的关键,根据名称我们可以理解为具有Xxx条件,当然它实际的意义也是如此,条件注解是一个系列,下面我们详细做出解释
    @ConditionalOnBean:当SpringIoc容器内存在指定Bean的条件
    @ConditionalOnClass:当SpringIoc容器内存在指定Class的条件
    @ConditionalOnExpression:基于SpEL表达式作为判断条件
    @ConditionalOnJava:基于JVM版本作为判断条件
    @ConditionalOnJndi:在JNDI存在时查找指定的位置
    @ConditionalOnMissingBean:当SpringIoc容器内不存在指定Bean的条件
    @ConditionalOnMissingClass:当SpringIoc容器内不存在指定Class的条件
    @ConditionalOnNotWebApplication:当前项目不是Web项目的条件
    @ConditionalOnProperty:指定的属性是否有指定的值
    @ConditionalOnResource:类路径是否有指定的值
    @ConditionalOnSingleCandidate:当指定Bean在SpringIoc容器内只有一个,或者虽然有多个但是指定首选的Bean
    @ConditionalOnWebApplication:当前项目是Web项目的条件
    以上注解都是元注解@Conditional演变而来的,根据不用的条件对应创建以上的具体条件注解。
    到目前为止我们还没有完成自动化配置starter,我们需要了解SpringBoot运作原理后才可以完成后续编码。

    接下来配置配置spring.factories让自动配置类生效,在spring.factories文件中配置
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=
    com.springboottest.starter.HelloServiceAutoConfiguration
    这里我们使用maven打包,其他模块就可以使用上面我们定义的starter了
    我们在vip-springboot-first中因人我们上面创建的starter

     在vip-springboot-first的pom文件中添加下面的依赖

        <dependency>
                <groupId>com.aitiguigu</groupId>
                <artifactId>springboottest-spring-boot-starter</artifactId>
                <version>0.0.1-SNAPSHOT</version>
            </dependency>

    controller引入自定义starter中的service调用业务:

    package com.tuling.springboot;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.springboottest.starter.HelloService;
    
    @RestController
    public class AA {
        
        
        @Autowired
        HelloService helloService;
        
        @RequestMapping("/hello")
        public String aa(){
            
            return helloService.sayHello("你好");
        }
        
    
    }
    在application.properties中配置下面属性
    server.port=8081
    spring.datasource.url=jdbc:mysql://localhost:3306/spring
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    
    # REDIS (RedisProperties)
    # Redisu6570u636Eu5E93u7D22u5F15uFF08u9ED8u8BA4u4E3A0uFF09
    spring.redis.database=0
    # Redisu670Du52A1u5668u5730u5740
    spring.redis.host=127.0.0.1
    # Redisu670Du52A1u5668u8FDEu63A5u7AEFu53E3
    spring.redis.port=6379
    # Redisu670Du52A1u5668u8FDEu63A5u5BC6u7801uFF08u9ED8u8BA4u4E3Au7A7AuFF09
    spring.redis.password=
    # u8FDEu63A5u6C60u6700u5927u8FDEu63A5u6570uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
    spring.redis.pool.max-active=8
    # u8FDEu63A5u6C60u6700u5927u963Bu585Eu7B49u5F85u65F6u95F4uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
    spring.redis.pool.max-wait=-1
    # u8FDEu63A5u6C60u4E2Du7684u6700u5927u7A7Au95F2u8FDEu63A5
    spring.redis.pool.max-idle=8
    # u8FDEu63A5u6C60u4E2Du7684u6700u5C0Fu7A7Au95F2u8FDEu63A5
    spring.redis.pool.min-idle=0
    # u8FDEu63A5u8D85u65F6u65F6u95F4uFF08u6BEBu79D2uFF09
    spring.redis.timeout=0
    
    ## rabbitmq config
    spring.rabbitmq.host=localhost
    spring.rabbitmq.port=5672
    spring.rabbitmq.username=springboot
    spring.rabbitmq.password=123456
    
    debug=true
    
    springboottest.hello.prefix=sajdjsakdsa
    springboottest.hello.suffix=2wwww
    在浏览器中访问结果如下

    接下来我们启动项目,在控制台查找是否存在我们的HelloAutoConfiguration日志输出

    在控制台可以看到我们的自定义starter的自动化配置已经生效了,并且根据@ConditionalOnMissingBean(HelloService.class)做出了条件注入HelloService实体bean到SpringIoc容器内

    我们的配置生效了,到目前为止我相信大家已经明白了我们application.properties配置文件为什么可以作为统一配置入口,为什么配置后可以被对应starter所使用

     【尚硅谷】springBoot技术 springboot admin的监控

    需要因人依赖


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

    整个应用的配置如下

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.tuling.springboot</groupId>
        <artifactId>vip-springboot-first</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>vip-springboot-first</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.10.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.2.2</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.2.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.1.1</version><!-- 版本号必须需要 -->
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
    
            <dependency>
                <groupId>com.aitiguigu</groupId>
                <artifactId>springboottest-spring-boot-starter</artifactId>
                <version>0.0.1-SNAPSHOT</version>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-amqp</artifactId>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>

    actoator默认给我们提供了下面很多的端口的端点信息

    端点(Endpoints)
    端点可用于监控应用或者与应用进行交互,Spring Boot包含很多内置的端点,每个断电都可以禁用或者启用,要访问远程端点必须通过JMX或者http进行暴露 。

    端点列表:

     我们在浏览器访问/beans提供的端口

     提示当前我们没有权限

    我们需要进行配置下

    三、去官网查看2.0暴露端点的方式
    
    方式1:
    
    # 启用端点 env
    management.endpoint.env.enabled=true
     
    # 暴露端点 env 配置多个,隔开
    management.endpoints.web.exposure.include=env
    方式2:
    
    方式1中的暴露方式需要一个一个去开启需要暴露的端点,方式2直接开启和暴露所有端点
    
    management.endpoints.web.exposure.include=*
    注意在使用Http访问端点时,需要加上默认/actuator 前缀
    
     
    
    
    
    
    ————————————————
    版权声明:本文为CSDN博主「wallfeacers」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_27385301/article/details/82899303

     我们来看下当前info接口的信息

    我们在配置文件中配置一info开头的配置

    server.port=8081
    spring.datasource.url=jdbc:mysql://localhost:3306/spring
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    
    # REDIS (RedisProperties)
    # Redisu6570u636Eu5E93u7D22u5F15uFF08u9ED8u8BA4u4E3A0uFF09
    spring.redis.database=0
    # Redisu670Du52A1u5668u5730u5740
    spring.redis.host=127.0.0.1
    # Redisu670Du52A1u5668u8FDEu63A5u7AEFu53E3
    spring.redis.port=6379
    # Redisu670Du52A1u5668u8FDEu63A5u5BC6u7801uFF08u9ED8u8BA4u4E3Au7A7AuFF09
    spring.redis.password=
    # u8FDEu63A5u6C60u6700u5927u8FDEu63A5u6570uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
    spring.redis.pool.max-active=8
    # u8FDEu63A5u6C60u6700u5927u963Bu585Eu7B49u5F85u65F6u95F4uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
    spring.redis.pool.max-wait=-1
    # u8FDEu63A5u6C60u4E2Du7684u6700u5927u7A7Au95F2u8FDEu63A5
    spring.redis.pool.max-idle=8
    # u8FDEu63A5u6C60u4E2Du7684u6700u5C0Fu7A7Au95F2u8FDEu63A5
    spring.redis.pool.min-idle=0
    # u8FDEu63A5u8D85u65F6u65F6u95F4uFF08u6BEBu79D2uFF09
    spring.redis.timeout=0
    
    ## rabbitmq config
    spring.rabbitmq.host=localhost
    spring.rabbitmq.port=5672
    spring.rabbitmq.username=springboot
    spring.rabbitmq.password=123456
    
    debug=true
    
    springboottest.hello.prefix=sajdjsakdsa
    springboottest.hello.suffix=2wwww
    
    ##actuator config
    # u542Fu7528u7AEFu70B9 env
    management.endpoint.env.enabled=true
     
    # u66B4u9732u7AEFu70B9 env u914Du7F6Eu591Au4E2A,u9694u5F00
    management.endpoints.web.exposure.include=env
    
    management.endpoints.web.exposure.include=*
    
    info.sb=aa

     可以看到配置的信息info信息

     

     现在我们要修改访问的路径,指定beans的访问路口

    server.port=8081
    spring.datasource.url=jdbc:mysql://localhost:3306/spring
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    
    # REDIS (RedisProperties)
    # Redisu6570u636Eu5E93u7D22u5F15uFF08u9ED8u8BA4u4E3A0uFF09
    spring.redis.database=0
    # Redisu670Du52A1u5668u5730u5740
    spring.redis.host=127.0.0.1
    # Redisu670Du52A1u5668u8FDEu63A5u7AEFu53E3
    spring.redis.port=6379
    # Redisu670Du52A1u5668u8FDEu63A5u5BC6u7801uFF08u9ED8u8BA4u4E3Au7A7AuFF09
    spring.redis.password=
    # u8FDEu63A5u6C60u6700u5927u8FDEu63A5u6570uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
    spring.redis.pool.max-active=8
    # u8FDEu63A5u6C60u6700u5927u963Bu585Eu7B49u5F85u65F6u95F4uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
    spring.redis.pool.max-wait=-1
    # u8FDEu63A5u6C60u4E2Du7684u6700u5927u7A7Au95F2u8FDEu63A5
    spring.redis.pool.max-idle=8
    # u8FDEu63A5u6C60u4E2Du7684u6700u5C0Fu7A7Au95F2u8FDEu63A5
    spring.redis.pool.min-idle=0
    # u8FDEu63A5u8D85u65F6u65F6u95F4uFF08u6BEBu79D2uFF09
    spring.redis.timeout=0
    
    ## rabbitmq config
    spring.rabbitmq.host=localhost
    spring.rabbitmq.port=5672
    spring.rabbitmq.username=springboot
    spring.rabbitmq.password=123456
    
    debug=true
    
    springboottest.hello.prefix=sajdjsakdsa
    springboottest.hello.suffix=2wwww
    
    ##actuator config
    # u542Fu7528u7AEFu70B9 env
    management.endpoint.env.enabled=false
     
    # u66B4u9732u7AEFu70B9 env u914Du7F6Eu591Au4E2A,u9694u5F00
    management.endpoints.web.exposure.include=env
    
    management.endpoints.web.exposure.include=*
    
    
    info.sb=aa
    indo.aa=bb
     上面的配置表示除了env之外的端口,其他的端口都可以访问

    接下来我们重点讲解下/health这个端口接口的信息

     这这些包下面

     暴露的endpoint为health,在浏览器就可以通过/health访问

    健康检查调用了

    @ReadOperation
    public Health health() {
    return this.healthIndicator.health();
    }

    这个方法

     
  • 相关阅读:
    Java反射之访问私有属性或方法
    java字符串中显示双引号
    什么导致spring事务失效
    ActiveMq性能优化
    JFrame关闭事件处理
    c3p0数据库连接池死锁问题
    Mongodb性能优化
    Spring事务配置的五种方式
    ActiveMq启动停止
    JScrollPane动态加载图片
  • 原文地址:https://www.cnblogs.com/kebibuluan/p/11694021.html
Copyright © 2020-2023  润新知