springboot常用总结(持续更新)

获取resource目录下得文件

System.getProperties().setProperty("webdriver.chrome.driver",
                SeleniumConfig.class.getClassLoader().getResource("chromedriver.exe").getPath());

一、异步线程池

1.1 Springboot自定义异步线程池以及异常捕获处理器

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
​
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
​
/**
 * 自定义异步线程池
 */
@Slf4j
@Configuration
public class AsyncConfig implements AsyncConfigurer {
​
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 线程池corePoolSize
        executor.setCorePoolSize(50);
        // 线程池maxPoolSize
        executor.setMaxPoolSize(100);
        //队列容量
        executor.setQueueCapacity(1000);
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 正常关闭的时候,等待任务执行完
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //等待1min
        executor.setAwaitTerminationSeconds(60);
        // 线程前缀
        executor.setThreadNamePrefix("imooc-qinyi-task-");
        executor.setKeepAliveSeconds(10);
        executor.initialize();
        return executor;
    }
​
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
​
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method,
                                                Object... params) {
                log.error("AsyncTask Error: {}, {}, {}",
                        ex.getMessage(),
                        method.getDeclaringClass().getName() + "." + method.getName(),
                        Arrays.toString(params));
            }
        };
    }
}

1.2 通过配置文件指定

spring.task.execution.pool.allow-core-thread-timeout=true
spring.task.execution.pool.keep-alive=60s
spring.task.execution.pool.core-size=50
spring.task.execution.pool.max-size=100
spring.task.execution.pool.queue-capacity=1000
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=60
spring.task.execution.thread-name-prefix=xxx-task

1.3 demo

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
​
@Service
public class MyAsyncService {
​
​
    public Future<List<String>> handlerTasks(Long timeout) {
        if(timeout !=  null && timeout > 0){
            try {
                TimeUnit.SECONDS.sleep(timeout);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return new AsyncResult<>(Arrays.asList("1", "2"));
    }
}

二、Scheduler线程池

2.1 自定义线程池

@Configuration
public class SchedulerConfig {
​
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(5);
        taskScheduler.setThreadNamePrefix("xxx-task");
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.setAwaitTerminationSeconds(60);
        return taskScheduler;
    }
}

2.2 通过配置文件指定

spring.task.scheduling.pool.size=20
spring.task.scheduling.thread-name-prefix=xxx
spring.task.scheduling.shutdown.await-termination=true
spring.task.scheduling.shutdown.await-termination-period=60

2.3 demo

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
​
import java.util.concurrent.TimeUnit;
​
@Service
@Slf4j
public class MySchedulerService {
​
    @Scheduled(fixedDelay = 3000)
    public void fixed() throws Exception {
        log.info("fixedDelay exec...");
    }
​
    @Scheduled(fixedRate = 5000)
    public void fixedRateTask() {
        log.info("fixedRate exec...");
    }
    
    /**
    * 以补偿方式运行,2s调度,运行3s,3s之后马上执行,而不是再等2s
    **/
    @Scheduled(fixedRate = 2000)
    public void fixedRateTask2s() throws InterruptedException {
        log.info("fixedRate2s exec begin...");
        TimeUnit.SECONDS.sleep(3000);
        log.info("fixedRate2s exec begin...");
    }
​
    // cron表达式在线网址https://cron.qqe2.com/
    @Scheduled(cron="0 0/1 * * * ?")
    public void cronTask() throws InterruptedException {
        log.info("cronTask exec ...");
    }
}

三、Spring上下文

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import base.utils.SpringHelper;
​
@Component("applicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware {
​
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringHelper.setApplicationContext(applicationContext);
    }
}
​
import org.springframework.context.ApplicationContext;
​
public class SpringHelper {
​
    private static ApplicationContext applicationContext;
​
    /**
     * @param applicationContext
     */
    public static void setApplicationContext(ApplicationContext applicationContext) {
        SpringHelper.applicationContext = applicationContext;
    }
​
    public static <T> T popBean(Class<T> clazz) {
        if (applicationContext == null)
            return null;
        return applicationContext.getBean(clazz);
    }
​
    public static <T> T popBean(String name, Class<T> clazz) {
        if (applicationContext == null)
            return null;
        return applicationContext.getBean(name, clazz);
    }
}

四、参数校验

public class BeanValidator {
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
​
    public BeanValidator() {
    }
​
    public static <T> Map<String, String> validate(T t, Class... groups) {
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator i$ = validateResult.iterator();
​
            while (i$.hasNext()) {
                ConstraintViolation constraintViolation = (ConstraintViolation) i$.next();
                errors.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
            }
​
            return errors;
        }
    }
​
    public static Map<String, String> validateForObjects(Object first, Object... others) {
        return others != null && others.length != 0 ? validateForList(Lists.asList(first, others)) : validate(first, new Class[0]);
    }
​
    public static Map<String, String> validateForList(Collection<?> collection) {
        Preconditions.checkNotNull(collection);
        Iterator i$ = collection.iterator();
​
        Map errors;
        do {
            if (!i$.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = i$.next();
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());
​
        return errors;
    }
}

五、tomcat,mysql配置

# 端口
server.port=8086
spring.profiles.active=pro
spring.application.name=dubbo-producer

# 日志
logging.level.demo=DEBUG
logging.level.com.alibaba.nacos.client.naming=ERROR
# jackson
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
# 数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=admin
spring.datasource.password=12345678
# Hikari will use the above plus the following to setup connection pooling
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.pool-name=dubbo-producer
spring.datasource.hikari.minimum-idle=1
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
# mybatis
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.mapper-locations=classpath:/mappers/*.xml
#tomcat
#等待队列长度
#server.tomcat.accept-count=1500
#默认值1w
#server.tomcat.max-connections=10000
#最大线程数(4h8g则800)
#server.tomcat.max-threads=1200
#最小线程数
#server.tomcat.min-space-threads=200
# redis
spring.redis.host=${redis.host:127.0.0.1}
spring.redis.port=${redis.port:6379}
spring.redis.lettuce.pool.max-active=${redis.pool.maxActive:300}
spring.redis.lettuce.pool.max-idle=${redis.pool.maxIdle:100}
spring.redis.lettuce.pool.max-wait=${redis.pool.maxWait:1000}
spring.redis.lettuce.pool.min-idle=${redis.minIdle:0}

# spring boot actuator端点启用和暴露
## * 可以用来表示所有的端点,例如,通过HTTP公开所有的端点
## * 在YAML中有特殊的含义,所以如果想使用include或者exclude包含所有的端点时要加上双引号
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
management.endpoints.promethus.enable=true
management.endpoint.health.show-details=always

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值