关于java:SpringBoot学习整合

4次阅读

共计 16702 个字符,预计需要花费 42 分钟才能阅读完成。

一、Docker

1、简介

Docker是一个开源的利用容器引擎,是一个轻量级容器技术。

Docker 反对将软件编译成一个镜像,而后在镜像中各种软件做好配置,将镜像公布进来,其余使用者能够间接应用这个镜像。

运行中的这个镜像称为容器,容器启动是十分疾速的。

2、外围概念

docker 主机(Host):装置了 Docker 程序的机器(Docker 间接装置在操作系统之上)。

docker 客户端(Client):连贯 docker 主机进行操作。

docker 仓库(Registry):用来保留各种打包好的软件镜像。Hub 提供了宏大的镜像汇合供应用。

docker 镜像(Images):软件打包好的镜像;放在 docker 仓库中。

docker 容器(Container):镜像启动后的实例称为一个容器,容器是独立运行的一个或一组利用。

应用 Docker 的步骤:

1)装置 Docker

2)去 Docker 仓库找到这个软件对应的镜像

3)应用 Docker 运行这个镜像,这个镜像就会生成一个 Docker 容器

4)对容器的启动进行就是对软件的启动进行

3、装置 Docker

1)装置 linux 虚拟机

​ 1)VMWare、VirtualBox(装置)

​ 2)导入虚拟机文件 centos7-kai.ova

​ 3)双击启动 linux 虚拟机; 应用 root/ 123456 登陆

​ 4)应用客户端连贯 linux 服务器进行命令操作

​ 5)设置虚拟机网络

​ 桥接网络 === 选好网卡 ==== 接入网线;

​ 6)设置好网络当前应用命令重启虚拟机的网络

service network restart

​ 7)查看 linux 的 ip 地址

ip addr

​ 8)应用客户端连贯 linux

2)在 linux 虚构机上安装 docker

步骤:

1、查看内核版本,必须是 3.10 及以上
uname -r
2、装置 docker
yum install docker
3、输出 y 确认装置
4、启动 docker
[root@localhost ~]# systemctl start docker
[root@localhost ~]# docker -v
Docker version 1.12.6, build 3e8e77d/1.12.6
5、开机启动 docker
[root@localhost ~]# systemctl enable docker
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.
6、进行 docker
systemctl stop docker

4、Docker 常用命令 & 操作

1)镜像操作

操作 命令 阐明
检索 docker search 关键字 eg:docker search redis 咱们常常去 dockerhub 上检索镜像的详细信息,如镜像的 TAG
拉取 docker pull 镜像名:tag tag 是可选的,tag 示意标签,多为软件的版本,默认是 latest
列表 docker images 查看所有本地镜像
删除 docker rmi image-id 删除指定的本地镜像

2)容器操作

操作 命令 阐明
运行 docker run –name container-name -d image-name
eg:docker run –name myredis –d redis
–name:自定义容器名
-d:后盾运行
image-name: 指定镜像模板
列表 docker ps(查看运行中的容器) 加上 -a:能够查看所有容器
进行 docker stop container-name/container-id 进行以后运行的容器
启动 docker start container-name/container-id 启动容器
删除 docker rm container-id 删除指定容器
端口映射 -p 6379:6379
eg:docker run -d -p 6379:6379 –name myredis docker.io/redis
-p: 主机端口 (映射到) 容器外部的端口
容器日志 docker logs container-name/container-id 查看容器的日志

实例操作:软件镜像(.exe 安装程序)—- 运行镜像 —- 产生一个容器(正在运行的软件,运行程序)

步骤:

1、搜寻镜像
[root@localhost ~]# docker search tomcat
2、拉取镜像
[root@localhost ~]# docker pull tomcat
3、依据镜像启动容器
docker run --name mytomcat -d tomcat:latest
4、docker ps  
查看运行中的容器
5、进行运行中的容器
docker stop  容器的 id
6、查看所有的容器
docker ps -a
7、启动容器
docker start 容器 id
8、删除一个容器
 docker rm 容器 id
9、启动一个做了端口映射的 tomcat
[root@localhost ~]# docker run -d -p 8888:8080 tomcat
-d:后盾运行
-p: 将主机的端口映射到容器的一个端口    主机端口: 容器外部的端口

10、为了演示简略敞开了 linux 的防火墙
service firewalld status;查看防火墙状态
service firewalld stop:敞开防火墙
11、查看容器的日志
docker logs container-name/container-id

更多命令参看
https://docs.docker.com/engin…
能够参考每一个镜像的文档

3)装置 MySQL 示例

docker pull mysql

谬误的启动

[root@localhost ~]# docker run --name mysql01 -d mysql
42f09819908bb72dd99ae19e792e0a5d03c48638421fa64cce5f8ba0f40f5846

mysql 退出了
[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                           PORTS               NAMES
42f09819908b        mysql               "docker-entrypoint.sh"   34 seconds ago      Exited (1) 33 seconds ago                            mysql01
538bde63e500        tomcat              "catalina.sh run"        About an hour ago   Exited (143) About an hour ago                       compassionate_
goldstine
c4f1ac60b3fc        tomcat              "catalina.sh run"        About an hour ago   Exited (143) About an hour ago                       lonely_fermi
81ec743a5271        tomcat              "catalina.sh run"        About an hour ago   Exited (143) About an hour ago                       sick_ramanujan


// 谬误日志
[root@localhost ~]# docker logs 42f09819908b
error: database is uninitialized and password option is not specified 
  You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD;这个三个参数必须指定一个

正确的启动

[root@localhost ~]# docker run --name mysql01 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
b874c56bec49fb43024b3805ab51e9097da779f2f572c22c695305dedd684c5f
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
b874c56bec49        mysql               "docker-entrypoint.sh"   4 seconds ago       Up 3 seconds        3306/tcp            mysql01

做了端口映射

[root@localhost ~]# docker run -p 3306:3306 --name mysql02 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
ad10e4bc5c6a0f61cbad43898de71d366117d120e39db651844c0e73863b9434
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
ad10e4bc5c6a        mysql               "docker-entrypoint.sh"   4 seconds ago       Up 2 seconds        0.0.0.0:3306->3306/tcp   mysql02

几个其余的高级操作

docker run --name mysql03 -v /conf/mysql:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag
把主机的 /conf/mysql 文件夹挂载到 mysqldocker 容器的 /etc/mysql/conf.d 文件夹外面
改 mysql 的配置文件就只须要把 mysql 配置文件放在自定义的文件夹下(/conf/mysql)docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
指定 mysql 的一些配置参数

二、SpringBoot 与数据拜访

1、JDBC

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.56.10:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver

成果:

​ 默认是用 org.apache.tomcat.jdbc.pool.DataSource 作为数据源,数据源的相干配置都在 DataSourceProperties 外面;

主动配置原理:

org.springframework.boot.autoconfigure.jdbc:

1、参考 DataSourceConfiguration,依据配置创立数据源,默认应用 Tomcat 连接池,能够应用 spring.datasource.type 指定自定义的数据源类型;

2、SpringBoot 默认能够反对

org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource...

3、自定义数据源类型 java

/**
 * Generic DataSource configuration.
 */
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {

   @Bean
   public DataSource dataSource(DataSourceProperties properties) {
       // 应用 DataSourceBuilder 创立数据源,利用反射创立响应 type 的数据源,并且绑定相干属性
      return properties.initializeDataSourceBuilder().build();
   }

}

4、DataSourceInitializer:ApplicationListener

​ 作用:

​ 1)runSchemaScripts(); 运行建表语句

​ 2)runDataScripts(); 运行插入数据的 sql 语句

默认只须要将文件命名为

schema-*.sql、data-*.sql
默认规定:schema.sql,schema-all.sql;能够应用   
    schema:
      - classpath:department.sql
      指定地位

5、操作数据库:主动配置了 JdbcTemplate 操作数据库

2、整合 Druid 数据源

导入 druid 数据源
@Configuration
public class DruidConfig {@ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){return  new DruidDataSource();
    }

    // 配置 Druid 的监控
    //1、配置一个治理后盾的 Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");// 默认就是容许所有拜访
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个 web 监控的 filter
    @Bean
    public FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

3、整合 MyBatis

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

步骤:

​ 1)配置数据源相干属性(见上一节 Druid)

​ 2)给数据库建表

​ 3)创立 JavaBean

4)注解

// 指定这是一个操作数据库的 mapper
@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

问题:

自定义 MyBatis 的配置规定,给容器中增加一个 ConfigurationCustomizer:

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}
// 应用 MapperScan 批量扫描所有的 Mapper 接口
@MapperScan(value = "com.kai.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
    }
}

5)配置文件版

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的地位
  mapper-locations: classpath:mybatis/mapper/*.xml  指定 sql 映射文件的地位

更多应用参照

http://www.mybatis.org/spring…

4、整合 SpringData JPA

1)SpringData 简介

2)整合 SpringData JPA

JPA:ORM(Object Relational Mapping)

1)编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;

// 应用 JPA 注解配置映射关系
@Entity // 通知 JPA 这是一个实体类(和数据表映射的类)@Table(name = "tbl_user") //@Table 来指定和哪个数据表对应; 如果省略默认表名就是 user;public class User {

    @Id // 这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)// 自增主键
    private Integer id;

    @Column(name = "last_name",length = 50) // 这是和数据表对应的一个列
    private String lastName;
    @Column // 省略默认列名就是属性名
    private String email;

2)编写一个 Dao 接口来操作实体类对应的数据表(Repository)

// 继承 JpaRepository 来实现对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}

3)根本的配置 JpaProperties

spring:  
 jpa:
    hibernate:
#     更新或者创立数据表构造
      ddl-auto: update
#    控制台显示 SQL
    show-sql: true

三、启动配置原理

几个重要的事件回调机制

配置在 META-INF/spring.factories

ApplicationContextInitializer

SpringApplicationRunListener

只须要放在 ioc 容器中

ApplicationRunner

CommandLineRunner

启动流程:

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

2、运行 run 办法

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(context, environment, listeners, applicationArguments,
            printedBanner);
       //prepareContext 运行实现当前回调所有的 SpringApplicationRunListener 的 contextLoaded();// 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);
   }
}

3、事件监听机制

配置在 META-INF/spring.factories

ApplicationContextInitializer

public class HelloApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {System.out.println("ApplicationContextInitializer...initialize..."+applicationContext);
    }
}

SpringApplicationRunListener

public class HelloSpringApplicationRunListener implements SpringApplicationRunListener {

    // 必须有的结构器
    public HelloSpringApplicationRunListener(SpringApplication application, String[] args){ }

    @Override
    public void starting() {System.out.println("SpringApplicationRunListener...starting...");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {Object o = environment.getSystemProperties().get("os.name");
        System.out.println("SpringApplicationRunListener...environmentPrepared.."+o);
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {System.out.println("SpringApplicationRunListener...contextPrepared...");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {System.out.println("SpringApplicationRunListener...contextLoaded...");
    }

    @Override
    public void finished(ConfigurableApplicationContext context, Throwable exception) {System.out.println("SpringApplicationRunListener...finished...");
    }
}

配置(META-INF/spring.factories)

org.springframework.context.ApplicationContextInitializer=\
com.kai.springboot.listener.HelloApplicationContextInitializer

org.springframework.boot.SpringApplicationRunListener=\
com.kai.springboot.listener.HelloSpringApplicationRunListener

只须要放在 ioc 容器中

ApplicationRunner

@Component
public class HelloApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {System.out.println("ApplicationRunner...run....");
    }
}

CommandLineRunner

@Component
public class HelloCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {System.out.println("CommandLineRunner...run..."+ Arrays.asList(args));
    }
}

四、自定义 starter

starter:

​ 1、这个场景须要应用到的依赖是什么

​ 2、如何编写主动配置

@Configuration  // 指定这个类是一个配置类
@ConditionalOnXXX  // 在指定条件成立的状况下主动配置类失效
@AutoConfigureAfter  // 指定主动配置类的程序
@Bean  // 给容器中增加组件

@ConfigurationPropertie 联合相干 xxxProperties 类来绑定相干的配置
@EnableConfigurationProperties // 让 xxxProperties 失效退出到容器中

主动配置类要能加载
将须要启动就加载的主动配置类,配置在 META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\

​ 3、模式:

启动器只用来做依赖导入;

专门来写一个主动配置模块;

启动器依赖主动配置:他人只须要引入启动器(starter)

mybatis-spring-boot-starter:自定义启动器名-spring-boot-starter

步骤:

1)启动器模块

<?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.kai.starter</groupId>
    <artifactId>kai-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 启动器 -->
    <dependencies>

        <!-- 引入主动配置模块 -->
        <dependency>
            <groupId>com.kai.starter</groupId>
            <artifactId>kai-spring-boot-starter-autoconfigurer</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

</project>

2)主动配置模块

<?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.kai.starter</groupId>
   <artifactId>kai-spring-boot-starter-autoconfigurer</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>kai-spring-boot-starter-autoconfigurer</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>

      <!-- 引入 spring-boot-starter;所有 starter 的根本配置 -->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>

   </dependencies>
</project>
package com.kai.starter;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "kai.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;}
}
package com.kai.starter;

public class HelloService {

    HelloProperties helloProperties;

    public HelloProperties getHelloProperties() {return helloProperties;}

    public void setHelloProperties(HelloProperties helloProperties) {this.helloProperties = helloProperties;}

    public String sayHellkai(String name){return helloProperties.getPrefix()+"-" +name + helloProperties.getSuffix();}
}
package com.kai.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)
public class HelloServiceAutoConfiguration {

    @Autowired
    HelloProperties helloProperties;
    @Bean
    public HelloService helloService(){HelloService service = new HelloService();
        service.setHelloProperties(helloProperties);
        return service;
    }
}

参考

视频教程

MyBatis-Spring-Boot-Starter

正文完
 0