一、简介

1、核心点

  敏捷开发、内置tomcat、减少xml配置

2、SpringBoot和微服务关联

  微服务基于SpringBoot

二、新建SpringBoot项目

1、核心依赖

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.21.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

2、访问静态资源

  SpringBoot默认提供静态资源目录位置需在classpath下,目录名需符合一下规则:

    /static

    /public

    /resources

    /META-INF/resources

3、全局异常捕获

  @ControllerAdvice
  public class GlobalExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String, Object> errorHandler(){
      Map<String, Object> result = new HashMap<>();
      result.put("errorCode", "500");
      result.put("errorMsg", "哦豁,出错了");
      return result;
    }
  }

 

4、SpringBoot整合页面

  4.1 SpringBoot官方建议使用模板引擎,不推荐使用JSP

  4.2 模板引擎

    即实现动态html,动态页面静态化

    默认的模板配置路径为:src/main/resources/templates

  4.3 分类

    FreeMarker:后缀为ftl

    Thymeleaf:

  4.4 FreeMarker

后台代码

@Controller
public class IndexController {

  @RequestMapping("/index")
  public String index(Map<String, String> model) {
    model.put("name", "happy");
    model.put("age", "22");
    return "index";
  }
}

 

freemarker文件:index.ftl

welcome: ${name} </br>
your age: ${age}

    配置信息

########################################################

###FREEMARKER (FreeMarkerAutoConfiguration)

########################################################

spring.freemarker.allow-request-override=false

spring.freemarker.cache=true

spring.freemarker.check-template-location=true

spring.freemarker.charset=UTF-8

spring.freemarker.content-type=text/html

spring.freemarker.expose-request-attributes=false

spring.freemarker.expose-session-attributes=false

spring.freemarker.expose-spring-macro-helpers=false

#spring.freemarker.prefix=

#spring.freemarker.request-context-attribute=

#spring.freemarker.settings.*=

spring.freemarker.suffix=.ftl

spring.freemarker.template-loader-path=classpath:/templates/

#comma-separated list

#spring.freemarker.view-names= # whitelist of view names that can be resolved

5、SpringBoot整合JSP

  就这样跳过吧

6、整合JDBCTemplate

  6.1 依赖

    <dependency>

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

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

    </dependency>

    <dependency>

      <groupId>mysql</groupId>

      <artifactId>mysql-connector-java</artifactId>

      <version>5.1.21</version>

    </dependency>

  6.2 配置文件

    spring.datasource.url=jdbc:mysql://localhost:3306/test

    spring.datasource.username=username

    spring.datasource.password=userpwd

    spring.datasource.driver-class-name=com.mysql.jdbc.Driver

7、整合JPA

  7.1 JPA是对Hibernate做了封装

  7.2 引入依赖

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

  7.3 编写实体类

    @Entity(name="users")
    public class User {
      @Id
      @GeneratedValue
      private Integer id;

      @Column
      private String name;

      @Column
      private Integer age;

    }

  7.4 编写DAO

    public interface UserDao extends JpaRepository<User, Integer>{}

    就可使用大部分增删改查API

8、整合mybatis

  8.1 依赖

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

  8.2 编写mapper接口

    public interface UserMapper {
      @Insert("insert into users(name, age) values(#{name}, #{age})")
      int insert(@Param("name") String name, @Param("age") Integer age);
    }

  8.3 入口类增加mapper接口扫包路径:@MapperScan(“basePackagesPath”)

 

三、SpringBoot进阶

1、整合多数据源

  1.1 如何区分数据源

    分包结构:根据包命中的某个定义字段,确定使用哪个数据源

    注解方式:

  1.2 整合过程

1、数据源信息application.properties

spring.datasource.db1.url=jdbc:mysql://192.168.236.128:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.db1.username=root
spring.datasource.db1.password=pwd
spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver


spring.datasource.db2.url=jdbc:mysql://192.168.236.128:3306/mytest?useUnicode=true&characterEncoding=utf-8
spring.datasource.db2.username=root
spring.datasource.db2.password=pwd
spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver

 

2、配置类,多个数据源需要多个配置类

@Configuration
@MapperScan(basePackages="springboot_demo.ch1.helloworld.db1", sqlSessionFactoryRef="db1SqlSessionFactory")
public class DB1Config {

  @Bean("db1DataSource")
  @ConfigurationProperties("spring.datasource.db1")
  @Primary  //表示spring启动时的默认数据源,否则会启动报错,只加在一个配置类数据源即可
  public DataSource getDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean("db1SqlSessionFactory")
  @Primary
  public SqlSessionFactory getSqlSessionFactoryBean(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);
    return sqlSessionFactoryBean.getObject();
  }

  @Bean("db1DataSourceTransactionManager")
  @Primary
  public DataSourceTransactionManager getTransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean("db1SqlSessionTemplate")
  @Primary
  public SqlSessionTemplate getSqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}

 

3、编写Mapper接口,调用即可

 

 2、整合分布式事务

  2.1 方法:将不同数据源的事务注册到第三方进行管理 

  2.2  spring-boot-starter-jta-atomikos

  2.3 配置类,不用配置DataSourceTransactionManager的Bean,已经整合进atomikos

  @Primary

      @Bean(name = "testDataSource")

      public DataSource testDataSource(DBConfig1 testConfig) throws SQLException {

            MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();

            mysqlXaDataSource.setUrl(testConfig.getUrl());

            mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

            mysqlXaDataSource.setPassword(testConfig.getPassword());

            mysqlXaDataSource.setUser(testConfig.getUsername());

            mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

 

            AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();

            xaDataSource.setXaDataSource(mysqlXaDataSource);

            xaDataSource.setUniqueResourceName("testDataSource");

 

            xaDataSource.setMinPoolSize(testConfig.getMinPoolSize());

            xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize());

            xaDataSource.setMaxLifetime(testConfig.getMaxLifetime());

            xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout());

            xaDataSource.setLoginTimeout(testConfig.getLoginTimeout());

            xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval());

            xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime());

            xaDataSource.setTestQuery(testConfig.getTestQuery());

            returnxaDataSource;

      }

 

3、整合AOP

  3.1 依赖:spring-boot-starter-aop

  3.2 开发:

@Aspect

@Component

publicclass WebLogAspect {

      private Logger logger = LoggerFactory.getLogger(getClass());

      @Pointcut("execution(public * springboot_demo.controller..*.*(..))")

      publicvoid webLog() {

      }

      @Before("webLog()")

      publicvoid doBefore(JoinPoint joinPoint) throws Throwable {

            // 接收到请求,记录请求内容

            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            HttpServletRequest request = attributes.getRequest();

            // 记录下请求内容

            logger.info("URL : " + request.getRequestURL().toString());

            logger.info("HTTP_METHOD : " + request.getMethod());

            logger.info("IP : " + request.getRemoteAddr());

            Enumeration<String> enu = request.getParameterNames();

            while (enu.hasMoreElements()) {

                  String name = (String) enu.nextElement();

                  logger.info("name:{},value:{}", name, request.getParameter(name));

            }

      }

      @AfterReturning(returning = "ret", pointcut = "webLog()")

      publicvoid doAfterReturning(Object ret) throws Throwable {

            // 处理完请求,返回内容

            logger.info("RESPONSE : " + ret);

      }

}

 

4、定时任务

  主类:EnableScheduling注解

  定时任务类:Component注入到容器中

  定时任务方法:Scheduled

  存在分布式下幂等问题

 

5、异步调用

  启动加上@EnableAsync ,需要执行异步方法上加入@Async

 

6、配置文件参数值读取

  6.1 application.properties中定义参数值

    如:name=test

  6.2 读取参数值,某个类中定义变量:

    @Value("${name}")

    private String propertyName;

  6.3 也可通过ConfigurationProperties注解,指定前缀(prefix),将参数注入到实体类中

 

7、多环境配置:

  主配置文件:application.properties中   spring.profiles.active=prod

  各环境配置文件:application-dev.properties, application-test.properties, application-prod.properties

 

8、修改tomcat信息:

  server.port=8090

  server.context-path=/myspringboot

 

9、打包:

  9.1 pom配置

  <build>

    <plugins>

      <plugin>

        <groupId>org.apache.maven.plugins</groupId>

        <artifactId>maven-compiler-plugin</artifactId>

        <configuration>

        <source>1.8</source>

        <target>1.8</target>

        </configuration>

      </plugin>

      <plugin>

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

        <artifactId>spring-boot-maven-plugin</artifactId>

        <configuration>

          <mainClass>包含main函数的全名</mainClass>

        </configuration>

        <executions>

          <execution>

            <goals>

              <goal>repackage</goal>

            </goals>

          </execution>

        </executions>

      </plugin>

    </plugins>

  </build>

 四、一些集成

1、集成rabbitmq

添加依赖:spring-boot-starter-amqp

生产者:使用AmqpTemplate

消费者:在消费方法上添加注解RabbitListener

posted on 2019-09-08 15:39  dysdhd  阅读(150)  评论(0编辑  收藏  举报