SpringBoot常用技术集成

SpringBoot中常用技术集成

  • 当同时存在properties配置文件和yml配置文件时,properties优先级高于yml。
  • springboot默认从config目录下读取配置信息,当没有config目录时,再从classpath下读取配置文件信息。
  • 当一个springboot项目中存在多个相同的配置文件时,properties > yml,config > classpath。
  • 当存在springcloud时,bootstrap.yml率先加载。

核心配置文件

#配置使用的配置文件环境
spring:
  profiles:
    active: dev
#配置端口号
server:
  port: 8080

1. @ConfigurationProperties

@ConfigurationProperties: 把配置文件的数据映射为java对象。

属性:prefix 配置文件中的某些key的开头的内容。


@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {

    private String name;

    private String website;

    private String address;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "SchoolInfo{" +
                "name='" + name + '\'' +
                ", website='" + website + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

application.properties


#自定义key=value
school.name=zahngsan
school.website=www.aaa.com
school.address=北京的大兴区

2. 集成Mybatis-Plus

1.导入依赖

  <!-- 数据持久层 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!--
        MySQL8驱动 可以兼容7的  但是需要加入8的驱动类  com.mysql.cj.
        连接字符串需要指定时区
        -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <!--<version>5.1.22</version>-->
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!-- mybatis-plus 代码生成器 -->

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!--
            mybtias 模板生成实体需要使用模板页面进行代码创建
        -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

2.核心配置文件

spring:
  datasource:
    url: jdbc:mysql://192.168.25.137:3306/dubbo?serverTimezone=Asia/Shanghai
    username: root
    password: MySQL5.7#
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    platform: mysql
    # 下面为连接池的补充设置
    druid:
      initialSize: 10   #初始化连接个数
      minIdle: 10       #最小空闲连接个数
      maxActive: 100    #最大连接个数
      maxWait: 60000    #获取连接时最大等待时间,单位毫秒。
      timeBetweenEvictionRunsMillis: 60000  #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      minEvictableIdleTimeMillis: 30000     #配置一个连接在池中最小生存的时间,单位是毫秒
      validationQuery: select 'x' #用来检测连接是否有效的sql,要求是一个查询语句。
      testWhileIdle: true       #建议配置为true,不影响性能,并且保证安全性。如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
      testOnBorrow: true        #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
      testOnReturn: false       #归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
      poolPreparedStatements: false #是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
      maxPoolPreparedStatementPerConnectionSize: -1 #要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
      filters: stat,wall,log4j #通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat,日志用的filter:log4j,防御sql注入的filter:wall
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      useGlobalDataSourceStat: false # 合并多个DruidDataSource的监控数据
      
###mybatis-plus
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  #删除数据   逻辑删除  物理删除
  global-config:
    # 逻辑删除配置
    db-config:
      # 删除前
      logic-not-delete-value: 1
      # 删除后
      logic-delete-value: 0

3.代码生成类

public class CodeGenerator {


    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //user.dir默认是整个大项目目录下
        String projectPath = System.getProperty("user.dir")+"/springboot-demo";
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("li");
        gc.setOpen(false);
        gc.setSwagger2(true);// 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/no4?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("xxx");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
       // pc.setModuleName(scanner("请输入模块名"));
        pc.setParent("com.li.application");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
       // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
       // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
      //strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

4.添加@Mapper或@MapperScan注解

注意:自动生成的实体类中时间类型为 LocalDateTime,格式为年月日时分秒,为java8推荐使用,LocalDate则不包括时分秒。实体类中需要使用 @JsonFormat注解格式化。

 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
 private LocalDateTime loginTime;

获取当前时间

 LocalDateTime.now()

3.Web组件的使用

1.注解方式

在启动类上加入**@ServletComponentScan**注解后,就可以使用@WebServlet注解等Servlet技术。

2.配置类注册
1.Servlet
@Configuration
public class WebApplictionConfig {

    //定义方法, 注册Servlet对象
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){

        //public ServletRegistrationBean(T servlet, String... urlMappings)
        //第一个参数是 Servlet对象, 第二个是url地址

        //ServletRegistrationBean bean = new ServletRegistrationBean( new MyServlet(),"/myservlet");


        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet( new MyServlet());
        bean.addUrlMappings("/login","/test"); // <url-pattern>


        return bean;
    }
}
2.过滤器
@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<AFilter> aFilterFilterRegistrationBean(){
        FilterRegistrationBean<AFilter> filterFilterRegistrationBean=new FilterRegistrationBean<>();;
        filterFilterRegistrationBean.setFilter(new AFilter());
        List<String> urls=new ArrayList<>();
        urls.add("/*");
        filterFilterRegistrationBean.setUrlPatterns(urls);
        //order是配置  过滤器 的顺序,越小越优先
        //1.xml 过滤映射在前的优先     2.注解  过滤器类的连音顺序
        filterFilterRegistrationBean.setOrder(2);
        return filterFilterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean<SpringBootFilter> filterFilterRegistrationBean(){
        FilterRegistrationBean<SpringBootFilter> filterFilterRegistrationBean=new FilterRegistrationBean<>();;
        filterFilterRegistrationBean.setFilter(new SpringBootFilter());
        List<String> urls=new ArrayList<>();
        urls.add("/*");
        filterFilterRegistrationBean.setUrlPatterns(urls);
        //order是配置  过滤器 的顺序
        //1.xml 过滤映射在前的优先     2.注解  过滤器类的连音顺序
        filterFilterRegistrationBean.setOrder(1);
        //restTemplate  通过httpClient(池化技术  避免资源浪费  每次请求都死创建一个新的连接)进行注入的
        //
        return filterFilterRegistrationBean;
    }
}
3.拦截器
@Configuration
public class LoginInterceptorConfig implements WebMvcConfigurer {
    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludes = new ArrayList<>();
        excludes.add("/res/**");  // res目录下的全部目录和文件
        excludes.add("/admin/toLogin");   // 去登录页
        excludes.add("/admin/login");  // 登录操作
        // 1.  registry.addInterceptor(new LoginInterceptor())       注册登录拦截器
        // 2.  addPathPatterns("/**")                                拦截器拦截所有地址
        // 3.  excludePathPatterns(excludes)                         指定不被拦截的路径
        List<String> userExcludes = new ArrayList<>();
        userExcludes.add("/user/toLogin");//登录页跳转
        userExcludes.add("/user/toRegisterUI");//注册页跳转
        userExcludes.add("/user/login");//登录
        userExcludes.add("/user/register");//注册
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/**","/cart/**","/order/**","/seller/**").excludePathPatterns(userExcludes);
        registry.addInterceptor(new AdminLoginInterceptor()).addPathPatterns("/admin/**").excludePathPatterns(excludes);
    }
}

4.集成Redis

1.pom依赖(二选一)


	 <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.5.RELEASE</version>
        </dependency>

2.配置类

@Configuration
@EnableAutoConfiguration
public class RedisConfig {

 // redisTemplate 序列化默认使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类


    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用Jackson2JsonRedisSerialize 替换默认序列化
       /* Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);*/
        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

3.配置文件

spring:
  redis:
    cluster:
      nodes:
        - 192.168.25.137:6380
        - 192.168.25.137:6381
        - 192.168.25.137:6382
        - 192.168.25.137:6383
        - 192.168.25.137:6384
        - 192.168.25.137:6385
        #默认值是5 一般当此值设置过大时,容易报:Too many Cluster redirections
      max-redirects: 3  # 获取失败 最大重定向次数
    lettuce:
      pool:
        max-active: 20 #连接池最大连接数(使用负值表示没有限制)
        max-idle: 8   #连接池中的最大空闲连接
        min-idle: 5   # 连接池中的最小空闲连接
    timeout: 6000   #连接超时时长(毫秒)

4.使用

  @Autowired
    private RedisTemplate<String,String> redisTemplate;

5.集成RabbitMQ

1.导入pom依赖

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

2.配置类

@Configuration
public class MQConfig {


    //声明交换机
    @Bean
    public DirectExchange spirngbootExchange(){
        return new DirectExchange("springbootExchange");
    }

    //声明队列
    @Bean
    public Queue springbootQueue(){
        return new Queue("springbootQueue");
    }

    //交换机队列绑定
    @Bean
    public Binding springExchangeBindSpringQueue(){
        return  BindingBuilder.bind(springbootQueue()).to(spirngbootExchange()).with("springboot");
    }

}

3.核心配置文件

#配置rabbitmq
spring:
  rabbitmq:
    host: 192.168.25.102
    port: 5672
    username: root
    password: root
    virtual-host: /
    listener:
      simple:
        acknowledge-mode: manual #手动确认消息
spring:
  rabbitmq:
    addresses: 192.168.100.120:5672,192.168.100.121:5672,192.168.100.122:5672
    username: root
    password: root
    #开启消息确认模式,新版本已经弃用
    #publisher-confirms: true
    #开启消息送达提示
    publisher-returns: true
    # springboot.rabbitmq.publisher-confirm 新版本已被弃用,现在使用 spring.rabbitmq.publisher-confirm-type = correlated 实现相同效果
    publisher-confirm-type: correlated
    virtual-host: /
    listener:
      type: simple
      simple:
        acknowledge-mode: auto #确认模式
        prefetch: 1 #限制每次发送一条数据。
        concurrency: 3 #同一个队列启动几个消费者
        max-concurrency: 3 #启动消费者最大数量
        #重试策略相关配置
        retry:
          # 开启消费者(程序出现异常)重试机制,默认开启并一直重试
          enabled: true
          # 最大重试次数
          max-attempts: 5
          # 重试间隔时间(毫秒)
          initial-interval: 3000

4.消息发送

    @Autowired
    private AmqpTemplate amqpTemplate;

    //给消息队列
   amqpTemplate.convertAndSend("searchExchange","admin:news",newsVo1);

5.消息监听消费

@Component
public class MQMsgListener {

    //设置消息的的监听方法  需要2个注解
    @RabbitListener(queues = "springbootQueue")
    //加入 信道 和msg
    //auto 没有异常时 进行自动确认 (异常类型 消息重新入队)
    //自动确认

    //手动确认
    public void bootMsg(Channel channel, Message message){
        System.out.println(new String(message.getBody()));
        //手动确认该消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.LogBack日志

<?xml version="1.0" encoding="UTF-8"?>
<configuration  scan="true" scanPeriod="60 seconds" debug="false">
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <!-- 在IDE中运行, 控制台输出全部日志 -->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        </filter>
        <encoder>
            <pattern>%date{yyyy-MM-dd HH:mm} | %highlight(%-5level) | %boldYellow(%thread) | %boldGreen(%logger{36}) | %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- 在IDE中运行, 不输出日志文件, 打包时level被portable-config-maven-plugin插件改为DEBUG, 输出日志文件 -->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUG</level>
        </filter>
        <File>D:/logs/logback.log</File>
        <!-- 按每小时滚动文件,如果一个小时内达到10M也会滚动文件, 滚动文件将会压缩成zip格式, 最多保留672个滚动文件 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logs/project-%d{yyyy-MM-dd-HH}.%i.zip</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>672</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{MM:dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="ErrorConsole" class="ch.qos.logback.core.ConsoleAppender">
        <!-- 在IDE中运行, 控制台输出全部日志, 打包时level被portable-config-maven-plugin插件改为OFF, 控制台不输出日志 -->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUG</level>
        </filter>
        <encoder>
            <pattern>%date{yyyy-MM-dd HH:mm:ss} | %highlight(%-5level) | %boldYellow(%thread) | %boldGreen(%logger{36}) | %msg%n</pattern>
        </encoder>
    </appender>

    <!-- project default level -->
    <logger name="com.oracle" level="INFO"/>
    <logger name="org.springframework.web" level="INFO"/>
    <logger name="org.springframework.core.env.PropertySourcesPropertyResolver" level="WARN"/>


    <!--日志级别-->
    <root level="INFO">
        <!--日志输出的目的地-->
        <appender-ref ref="Console"/>
        <appender-ref ref="RollingFile"/>
    </root>
</configuration>

7.Swegger2集成

Swagger注解

  • @Api()用于类;表示标识这个类是swagger的资源
  • @ApiOperation()用于方法;表示一个http请求的操作
  • @ApiParam()用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
  • @ApiModel()用于类表示对类进行说明,用于参数用实体类接收
  • @ApiModelProperty()用于方法,字段表示对model属性的说明或者数据操作更改
  • @ApiIgnore()用于类,方法,方法参数 表示这个方法或者类被忽略
  • @ApiImplicitParam() 用于方法 表示单独的请求参数
  • @ApiImplicitParams() 用于方法,包含多个@ApiImplicitParam

1.引入pom依赖

        <!--swagger2的jar包-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!--引入视觉的样式的UI-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2.配置类

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBootSwagger文档")
                .description("接口测试")
                .version("1.0")
                .build();
    }
}

3.地址栏通过http://localhost:8080/swagger-ui.html访问

8.阿里云OSS对象存储

1.pom依赖

   <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>

2.配置类

@Configuration
@ConfigurationProperties(prefix = "alibaba.oss")
@Data
public class OSSConfig {

    private String accessKey;

    private String accessSecret;

    private String endpoint;

    private String bucket;

}

3.自定义配置文件

#自定义配  阿里云对象存储的配置信息
alibaba:
  oss:
    accessKey: xxx
    accessSecret: xxx
    endpoint: oss-cn-hangzhou.aliyuncs.com
    bucket: xxx

4.使用

   /**
     * 阿里云对象存储文件上传
     */
    @PostMapping("/upload")
    public String upload(MultipartFile img) throws IOException {
        OSSClient client = new OSSClient(ossConfig.getEndpoint(),ossConfig.getAccessKey(),ossConfig.getAccessSecret());
        client.putObject(ossConfig.getBucket(),"testOssFile.jpg",img.getInputStream());
        return "ok";
    }

9.HttpClient

1.导入依赖

       <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4</version>
        </dependency>

2.配置类

@Configuration
@ConfigurationProperties(prefix = "http")
@Data
public class HttpCilentConfig {
    private Integer maxTotal;// 最大连接

    private Integer defaultMaxPerRoute;// 每个host的最大连接

    private Integer connectTimeout;// 连接超时时间

    private Integer connectionRequestTimeout;// 请求超时时间

    private Integer socketTimeout;// 响应超时时间

    /**
     * HttpClient连接池
     * @return
     */
    @Bean
    public HttpClientConnectionManager httpClientConnectionManager() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        return connectionManager;
    }

    /**
     * 注册RequestConfig
     * @return
     */
    @Bean
    public RequestConfig requestConfig() {
        return RequestConfig.custom().setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)
                .build();
    }

    /**
     * 注册HttpClient
     * @param manager
     * @param config
     * @return
     */
    @Bean
    public HttpClient httpClient(HttpClientConnectionManager manager, RequestConfig config) {
        return HttpClientBuilder.create().setConnectionManager(manager).setDefaultRequestConfig(config)
                .build();
    }
    /**
     * 使用连接池管理连接
     * @param httpClient
     * @return
     */
    @Bean
    public ClientHttpRequestFactory requestFactory(HttpClient httpClient) {
        return new HttpComponentsClientHttpRequestFactory(httpClient);
    }
    /**
     * 使用HttpClient来初始化一个RestTemplate
     * @param requestFactory
     * @return
     */
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) {
        RestTemplate template = new RestTemplate(requestFactory);

        List<HttpMessageConverter<?>> list = template.getMessageConverters();
        for (HttpMessageConverter<?> mc : list) {
            if (mc instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8"));
            }
        }
        return template;
    }
}

3.自定义核心配置文件

#httpClient
http:
  maxTotal: 300
  defaultMaxPerRoute: 50
  connectTimeout: 1000
  connectionRequestTimeout: 500
  socketTimeout: 5000
  staleConnectionCheckEnabled: true

4.使用restTemplate

@Autowired
private RestTemplate restTemplate;



   String url="http://v.juhe.cn/toutiao/index?type=top&key=xxx";
        RemoteResponseVo remoteResponseVo = this.restTemplate.getForObject(url, RemoteResponseVo.class);

10.Task定时任务

@Component
@EnableScheduling
public class RemoteNewsJob {

    @Autowired
    private RemoteNewsConfig remoteNewsConfig;

    //21:30执行,项目启动后开始计算执行
    //Spring的task任务调度不能够设置开启状态和停止
    @Scheduled(cron = "0 58 8 ? * *")
    public void remoteTitleNews(){
       this.remoteNewsConfig.remoteNewsTitle();
    }

    @Scheduled(cron = "0 11 9 ? * *")
    public void remoteContentNews(){
        this.remoteNewsConfig.remoteNewsContent();
    }


}

cron规则

"0/10 * * * * ?" 每10秒触发   
"0 0 12 * * ?" 每天中午12点触发   
"0 15 10 ? * *" 每天上午10:15触发   
"0 15 10 * * ?" 每天上午10:15触发   
"0 15 10 * * ? *" 每天上午10:15触发   
"0 15 10 * * ? 2005" 2005年的每天上午10:15触发   
"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发   
"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发   
"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发   
"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发   
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发   
"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发   
"0 15 10 15 * ?" 每月15日上午10:15触发   
"0 15 10 L * ?" 每月最后一日的上午10:15触发   
"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发   
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发   
"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发   
每隔5秒执行一次:*/5 * * * * ?   
每隔1分钟执行一次:0 */1 * * * ?   
每天23点执行一次:0 0 23 * * ?   
每天凌晨1点执行一次:0 0 1 * * ?   
每月1号凌晨1点执行一次:0 0 1 1 * ?   
每月最后一天23点执行一次:0 0 23 L * ?   
每周星期天凌晨1点实行一次:0 0 1 ? * L   
在26分、29分、33分执行一次:0 26,29,33 * * * ?   
每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?   

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值