java——springboot(4)

Docker:

Docker是一个开源的应用容器引擎;是一个轻量级容器技术;
Docker支持将软件编译成一个镜像;然后在镜像中各种软件做好配置,将镜像发布出去,其他使用者可以直接使
用这个镜像;
 
使用步骤(linux系统):
1、安装docker:yum install docker
  启动docker:systemctl start docker
  开机自启动:systemctl anable docker
  关闭docker:systemctl stop docker
2、镜像操作:
   

 

 3、容器操作:

根据镜像启动容器:docker run ‐‐name mytomcat ‐d tomcat:latest

如果需要映射端口,则使用-p参数:docker run ‐d ‐p 8888:8080 tomcat

查看运行中的容器:docker ps

查看系统上所有的容器:docker ps ‐a

进入一个容器中:docker exec -it 容器id 容器落脚点;例:docker exec -it acbbd41debe7 /bin/bash

退出容器:exit

将容器提交成一个镜像:docker commit -a=作者名 -m=备注 容器id 命名的镜像

容器和镜像的关系:容器=镜像+读写层,这个读写层你可以看作是类似电脑运行时内存般的东西,必须要在镜像运行成容器时才会出现,我们也可以通过这个读写层修改自定义容器,而镜像是不能修改的,但是容器可以提交变成一个新镜像;

你可以把镜像当作磁盘,运行镜像时就是加载磁盘里文件到内存,做完操作后我们可以把文件存到另一个磁盘,此时就类似生成另一个容器;

将项目打成一个镜像的流程:

1、准备好jar或war包

2、编写Dockerfile文件

编写时常用的命令:

 

Dockerfile例子:

FROM openjdk:11
VOLUME /tmp
ADD docker_learn.jar app.jar
RUN bash -c 'touch /app.jar'
EXPOSE 8080
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

3、执行docker bulid指令

docker bulid -t 命名标签  .

这个命令后面的点表示用当前目录下的Dockerfile,记得要加上

我们在配置我们的容器时,会经常需要修改容器里的配置文件,不过是不能直接在容器里改的,因为我们主机里并没有这个文件,这个似乎就经常会用到一个命令:docker cp 容器id:容器里文件所在位置  所要拷贝到的主机位置

拷贝进容器就后面两个参数互换就好

即需要把容器里的文件拷贝到主机里去进行修改;

启动一个容器:docker start 容器id或容器别名 
删除一个容器:docker rm 容器id或容器别名
查看容器日志:docker logs container‐name/container‐id
把主机的/conf/mysql文件夹挂载到 mysqldocker容器的/etc/mysql/conf.d文件夹里面,这样以后改mysql的配置文件就只需要把mysql配置文件放在自定义的文件夹下(/conf/mysql):
docker run ‐‐name mysql03 ‐v /conf/mysql:/etc/mysql/conf.d ‐e MYSQL_ROOT_PASSWORD=my‐secret‐pw ‐d mysql:tag
 
 
数据访问:
JDBC:
效果:
默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源;
数据源的相关配置都在DataSourceProperties里面;
自动配置原理:
org.springframework.boot.autoconfifigure.jdbc:
1、参考DataSourceConfifiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用
spring.datasource.type指定自定义的数据源类型;
2、SpringBoot默认可以支持;
org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource、

 

3、自定义数据源类型
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {
 @Bean
   public DataSource dataSource(DataSourceProperties properties) {
       //使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
      return properties.initializeDataSourceBuilder().build();
   }
}

然后在配置文件配置spring.datasource.type属性即可;

4、DataSourceInitializer:ApplicationListener;

作用:

1)、runSchemaScripts();运行建表语句;
2)、runDataScripts();运行插入数据的sql语句;
可将sql文件放入项目中,然后通过配置文件指定就可在运行项目时自动建表;如:

 

 导入druid类型的数据源:

编写配置类:

package com.example.demo.config;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
@ConditionalOnClass(com.alibaba.druid.pool.DruidDataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = true)
public class DruidDataSource {
    public DataSource dataSourceOne() {
        return DruidDataSourceBuilder.create().build();
        
    }

    @Bean
    public ServletRegistrationBean druidStatViewServlet(){
        //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //添加初始化参数:initParams
        //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter("deny","192.168.1.73");
        //登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername","admin");
        servletRegistrationBean.addInitParameter("loginPassword","123456");
        //是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean druidStatFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

这里注入的ServletRegistrationBean、和FilterRegistrationBean都是druid特有的功能,可以实时监控数据库以及web的访问情况;需要注意的是得在配置中配好数据池的类型;

 

整合Mybatis:

注解版:

先在主进口类那里加上@MapperScan()注解,告诉容器应该扫描哪些mapper文件:

 

 然后编写mapper类:

package com.example.demo.Mapper;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.demo.bean.Department;

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

@Mapper指定这个操作数据库的mapper

通过controller调用mapper:

package com.example.demo.contoller;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.Mapper.DepartmentMapper;
import com.example.demo.Mapper.EmployeeMapper;
import com.example.demo.bean.Department;
import com.example.demo.bean.Employee;

@RestController
public class DeptController {
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id) {
        return departmentMapper.getDeptById(id);
    }
    @GetMapping("/dept")
    public Department insertDept(Department department) {
        departmentMapper.insertDept(department);
        return department;
    }
    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id) {
        return employeeMapper.getEmpById(id);
    }
    
    
}

 

修改mabatis的配置规则,可以给容器添加一个ConfigurationCustomizer;比如,让实体类的dId能匹配上数据库的d_id,即开启自动驼峰转换功能:

package com.example.demo.config;

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
@org.springframework.context.annotation.Configuration
public class MybatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomzer() {
        return new ConfigurationCustomizer() {
            
            @Override
            public void customize(Configuration configuration) {
                // TODO Auto-generated method stub
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

 

 

配置文件版:在配置文件加上配置:

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
     <settings>
         <setting name="mapUnderscoreToCamelCase" value = "true"/>
     </settings>
</configuration>

mapper类:

package com.example.demo.Mapper;

import com.example.demo.bean.Employee;

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);
}

controller类:

@Autowired
    EmployeeMapper employeeMapper;
@GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id) {
        return employeeMapper.getEmpById(id);
    }
    

 

 

整合SpringData JPA

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):

package com.example.demo.Dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.demo.entity.User;

public interface UserRepository extends JpaRepository<User, Integer> {
    

}

3、配置好配置文件:

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.112.51:3306/jpa
    driver-class-name: com.mysql.jdbc.Driver
  jpa: 
    hibernate: 
      ddl-auto: update#更新或者创建数据表结构
    show-sql: true#显示台输出sql语句
     

最后再通过控制器controller来调用:

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.Dao.UserRepository;
import com.example.demo.entity.User;

@RestController
public class UserController {
    @Autowired
    UserRepository userRepository;
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id) {
        User user = userRepository.findById(id).orElse(null);
        return user;
    }
    @GetMapping("/user")
    public User insertUser(User user) {
        User save = userRepository.save(user);
        return save;
    }
}

 

 

 

 

posted @ 2020-06-24 17:53  xiao兆  阅读(152)  评论(0编辑  收藏  举报