springboot搭建项目

===================================

 

pom文件中引入springboot父类依赖,所有springboot项目都必须依赖



<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>



 

配置application文件



#端口
spring:
    port: 8080

#数据库连接
spring:
    datasource:
        url:jdbc:oracle:thin:@localhost:1521:serverName
        userName: userName
        password: password
        driver-calss-name: oracle.jdbc.driver.OracleDriver
        type: com.alibaba.druid.pool.DruidDataSource



 

配置启动类



package com.cccc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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



 

依赖springMVC,开启springmvc框架



<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!-- springboot用webflux代替web -->
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
        <version>2.0.3.RELEASE</version>
    </dependency>



 

依赖mybatis,集成mybatis框架



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



 

依赖数据jdbc驱动,与数据库连接



<dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>



 

依赖第三方数据源Druid,配置数据源信息



<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>



 

配置数据源和事务



package com.cccc.config;


import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
@Data
@MapperScan(basePackages = "com.cccc.mapper", sqlSessionFactoryRef = "sessionFactory")
public class DruidConfig {

    private String url;
    private String userName;
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driver;

    @Bean("dataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driver);
        return dataSource;
    }

    @Bean("sessionFactory")
    public SqlSessionFactory sessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setTypeAliasesPackage("com.cccc.pojo");
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean("sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("transactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}



 

依赖配置文件驱动,可添加也可不添加此依赖



<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>



 

依赖springboot测试框架



<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>



 

test示例



package com.cccc;

import org.junit.Assert;
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.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class AirwayServiceTest {


    @Autowired
    private UserService userService;


    @Test
    public void testList() {
        List<User> list = userService.getList();
        //如果插入成功 num为1,否则提示插入失败
        Assert.assertTrue("num不为1,插入失败", num == 1);
    }

}



 

springboot集成通用mapper框架,仅针对单表操作



<dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.3</version>
        </dependency>



 

springboot集成swagger2文档框架



<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

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



 

swagger2配置类



package com.cccc;

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 Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cccc"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("新项目使用swagger2框架")
                .termsOfServiceUrl("")
                .version("1.0.0")
                .build();
    }
}



 

swagger2示例,访问http://localhost:8080/swagger-ui.html



package com.cccc.controller;

import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Api(tags = "基础信息-特殊旅客类别")
public class SpecialPassengerTypeController {
    private Logger logger = LoggerFactory.getLogger(SpecialPassengerTypeController.class);

    @Value("${server.port}")
    private String port;

    @Autowired
    private UserService userService;


    @GetMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询用户信息", notes = "支持模糊查询")
    @ApiImplicitParam(name = "param", value = "查询条件对象", required = false, dataType = "User", paramType = "query")
    public String getSpecialList(User param){
        return "success";
    }
}



 

添加监控中心actuator



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



 

在application中配置监控所有权限



management:
  endpoints:
    web:
      exposure:
        include: "*"



访问http://localhost:8080/actuator/beans查看spring中所有bean的信息

访问http://localhost:8080/actuator/autoconfig查看springboot所有自动配置

访问http://localhost:8080/actuator/configprops查看所有配置属性

访问http://localhost:8080/actuator/mappings查看所有映射路径

访问http://localhost:8080/actuator/env查看环境变量

访问http://localhost:8080/actuator/metrics查看度量指标 

访问http://localhost:8080/actuator/trace查看追踪路径

访问http://localhost:8080/actuator/dump查看运行线程

访问http://localhost:8080/actuator/health查看健康指标

 

服务注册consul



<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-config</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>



application中配置consul信息



spring:
  application:
    name: config-param
  cloud:
    consul:
      host: localhost
      port: 8500
      enable: true
      discovery:
        healthCheckPath: /actuator/health
        healthCheckInterval: 15s
        instance-id: config-param



启动类配置@EnableDiscoveryClient

启动consul服务器 consul agent -dev,访问http://localhost:8500


springboot admin管理服务



<dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-server</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-server-ui</artifactId>
            <version>2.0.1</version>
        </dependency>



启动类添加 @EnableAdminServer,访问http://localhost:port

添加boot admin的配置



spring:
  application:
    name: config-param
  boot:
    admin:
      client:
        url: http://localhost:8080



 

服务调用feign,springboot2.0依赖的feign为openfeign



<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
            <version>1.4.4.RELEASE</version>
        </dependency>



启动类添加@EnableFeignClients,配置feign调用接口

application.yml添加配置,开启feign调用



feign:
  hystrix:
    enabled: true



 



package com.cccc.feign;

import com.cccc.dto.ConfigParamDTO;
import com.cccc.fallback.ConfigTypeServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@FeignClient(value = "data-service", path = "/config", fallback = ConfigServiceFallback.class)
public interface ConfigService {

    @PostMapping(value = "/getList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    String getType(@RequestBody Config param);
}



fallback降级



package com.cccc.fallback;

import org.springframework.stereotype.Component;

@Component
public class ConfigServiceFallback implements ConfigService {
    @Override
    public String getType(Config param) {
        return "调用feign失败";
    }
}



 

断路器hystrix



<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.4.RELEASE</version>
        </dependency>



 启动类添加@EnableCircuitBreaker

Hystix示例



package com.cccc.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.cccc.dto.ConfigParamDTO;
import com.cccc.feign.ConfigTypeService;
import com.cccc.mapper.ConfigParamMapper;
import com.cccc.pojo.ConfigParam;
import com.cccc.service.ConfigParamService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ConfigServiceImpl implements ConfigService {

    @Autowired
    private ConfigMapper mapper;

    @Override
    @HystrixCommand(fallbackMethod = "hystrix")
    public List<Config> getList(int s) {
        return mapper.getList();
    }
    
    public List<Config> hystrix(int s) {
        List<Config> list = Lists.newArrayList();
        return list;
    }

}



 

springcloud链路跟踪工具 ,路径调用全过程,集成zipkin框架

配置zipkin服务server



<dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-server</artifactId> <version>2.9.4</version> </dependency> <dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-autoconfigure-ui</artifactId> <version>2.9.4</version> </dependency>



 

在启动类添加@EnableZipkinServer开启zipkin服务

配置服务到zipkin



<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>



配置application的zipkin地址信息



spring:
  zipkin:
    base-url: http://localhost:8888
    locator:
      discovery:
        enabled: true
  sleuth:
    sampler:
      percentage: 0.1



 

springboot读取配置文件properties,读取自定义配置文件

1、使用@PropertySource("classpath:user.properties") + @Value("${}"),前提必须有属性的set方法,spring 中的bean才有初始化配置属性 ,注入取对象@Autowired



package com.cccc.service.impl;

import com.cccc.service.PropertyService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@Service
@PropertySource("classpath:stu.properties")
@Data
public class PropertyServiceImpl implements PropertyService {

    @Value("${stu.age}")
    private String age;

    @Value("${stu.name}")
    private String name;

    @Override
    public String getProperties() {
        return "addr = " + name + " --> age = " + age;
    }
}



stu.properties文件



stu.name=lisi
stu.age=18




2、@PropertySource("classpath:stu.properties") + @ConfigurationProperties(prefix = "stu"),前提必须有属性的set方法,spring 中的bean才有初始化配置属性,以注入方式取bean @Autowired



package com.cccc.service.impl;

import com.cccc.service.PropertyService;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@Service
@PropertySource("classpath:stu.properties")
@ConfigurationProperties(prefix = "stu")
@Data
public class PropertyServiceImpl implements PropertyService {

    private String age;

    private String name;

    @Override
    public String getProperties() {
        return "addr = " + name + " >>> age = " + age;
    }
}



 

 3、新建配置类 + 注入



package com.cccc.Config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@PropertySource("classpath:stu.properties")
@ConfigurationProperties(prefix = "stu")
@Data
@Configuration
public class UserConfig {
    private String name;
    private String age;
}



引用,注入进来



package com.cccc.service.impl;

import com.cccc.Config.UserConfig;
import com.cccc.service.PropertyService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@Service
@PropertySource("classpath:stu.properties")
@ConfigurationProperties(prefix = "stu")
@Data
public class PropertyServiceImpl implements PropertyService {

    @Autowired
    private UserConfig userConfig;

    @Override
    public String getProperties() {
        return "addr = " + userConfig.getName() + " >>> age = " + userConfig.getAge();
    }
}



 

日志监控:sentry框架

网关zuul框架