springboot常用总结(持续更新)

你的名字 2022-12-24 12:52 340阅读 0赞

一、异步线程池

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

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.scheduling.annotation.AsyncConfigurer;
  5. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  6. import java.lang.reflect.Method;
  7. import java.util.Arrays;
  8. import java.util.concurrent.Executor;
  9. import java.util.concurrent.ThreadPoolExecutor;
  10. /**
  11. * 自定义异步线程池
  12. */
  13. @Slf4j
  14. @Configuration
  15. public class AsyncConfig implements AsyncConfigurer {
  16. @Override
  17. public Executor getAsyncExecutor() {
  18. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  19. // 线程池corePoolSize
  20. executor.setCorePoolSize(50);
  21. // 线程池maxPoolSize
  22. executor.setMaxPoolSize(100);
  23. //队列容量
  24. executor.setQueueCapacity(1000);
  25. // 拒绝策略
  26. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
  27. // 正常关闭的时候,等待任务执行完
  28. executor.setWaitForTasksToCompleteOnShutdown(true);
  29. //等待1min
  30. executor.setAwaitTerminationSeconds(60);
  31. // 线程前缀
  32. executor.setThreadNamePrefix("imooc-qinyi-task-");
  33. executor.setKeepAliveSeconds(10);
  34. executor.initialize();
  35. return executor;
  36. }
  37. @Override
  38. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  39. return new AsyncUncaughtExceptionHandler() {
  40. @Override
  41. public void handleUncaughtException(Throwable ex, Method method,
  42. Object... params) {
  43. log.error("AsyncTask Error: {}, {}, {}",
  44. ex.getMessage(),
  45. method.getDeclaringClass().getName() + "." + method.getName(),
  46. Arrays.toString(params));
  47. }
  48. };
  49. }
  50. }

1.2 通过配置文件指定

  1. spring.task.execution.pool.allow-core-thread-timeout=true
  2. spring.task.execution.pool.keep-alive=60s
  3. spring.task.execution.pool.core-size=50
  4. spring.task.execution.pool.max-size=100
  5. spring.task.execution.pool.queue-capacity=1000
  6. spring.task.execution.shutdown.await-termination=true
  7. spring.task.execution.shutdown.await-termination-period=60
  8. spring.task.execution.thread-name-prefix=happylaishop-task

1.3 demo

  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.concurrent.Future;
  4. import java.util.concurrent.TimeUnit;
  5. @Service
  6. public class MyAsyncService {
  7. public Future<List<String>> handlerTasks(Long timeout) {
  8. if(timeout != null && timeout > 0){
  9. try {
  10. TimeUnit.SECONDS.sleep(timeout);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. return new AsyncResult<>(Arrays.asList("1", "2"));
  16. }
  17. }

二、Scheduler线程池

2.1 自定义线程池

  1. @Configuration
  2. public class SchedulerConfig {
  3. @Bean
  4. public TaskScheduler taskScheduler() {
  5. ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
  6. taskScheduler.setPoolSize(5);
  7. taskScheduler.setThreadNamePrefix("happylaishop-task");
  8. taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
  9. taskScheduler.setAwaitTerminationSeconds(60);
  10. return taskScheduler;
  11. }
  12. }

2.2 通过配置文件指定

  1. spring.task.scheduling.pool.size=20
  2. spring.task.scheduling.thread-name-prefix=happylaishop
  3. spring.task.scheduling.shutdown.await-termination=true
  4. spring.task.scheduling.shutdown.await-termination-period=60

2.3 demo

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.scheduling.annotation.Scheduled;
  3. import org.springframework.stereotype.Service;
  4. import java.util.concurrent.TimeUnit;
  5. @Service
  6. @Slf4j
  7. public class MySchedulerService {
  8. @Scheduled(fixedDelay = 3000)
  9. public void fixed() throws Exception {
  10. log.info("fixedDelay exec...");
  11. }
  12. @Scheduled(fixedRate = 5000)
  13. public void fixedRateTask() {
  14. log.info("fixedRate exec...");
  15. }
  16. /**
  17. * 以补偿方式运行,2s调度,运行3s,3s之后马上执行,而不是再等2s
  18. **/
  19. @Scheduled(fixedRate = 2000)
  20. public void fixedRateTask2s() throws InterruptedException {
  21. log.info("fixedRate2s exec begin...");
  22. TimeUnit.SECONDS.sleep(3000);
  23. log.info("fixedRate2s exec begin...");
  24. }
  25. // cron表达式在线网址https://cron.qqe2.com/
  26. @Scheduled(cron="0 0/1 * * * ?")
  27. public void cronTask() throws InterruptedException {
  28. log.info("cronTask exec ...");
  29. }
  30. }

三、Spring上下文

  1. import org.springframework.beans.BeansException;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.ApplicationContextAware;
  4. import org.springframework.stereotype.Component;
  5. import top.happylaishop.base.utils.SpringHelper;
  6. @Component("applicationContextHelper")
  7. public class ApplicationContextHelper implements ApplicationContextAware {
  8. @Override
  9. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  10. SpringHelper.setApplicationContext(applicationContext);
  11. }
  12. }
  13. import org.springframework.context.ApplicationContext;
  14. public class SpringHelper {
  15. private static ApplicationContext applicationContext;
  16. /**
  17. * @param applicationContext
  18. */
  19. public static void setApplicationContext(ApplicationContext applicationContext) {
  20. SpringHelper.applicationContext = applicationContext;
  21. }
  22. public static <T> T popBean(Class<T> clazz) {
  23. if (applicationContext == null)
  24. return null;
  25. return applicationContext.getBean(clazz);
  26. }
  27. public static <T> T popBean(String name, Class<T> clazz) {
  28. if (applicationContext == null)
  29. return null;
  30. return applicationContext.getBean(name, clazz);
  31. }
  32. }

四、参数校验

  1. public class BeanValidator {
  2. private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
  3. public BeanValidator() {
  4. }
  5. public static <T> Map<String, String> validate(T t, Class... groups) {
  6. Validator validator = validatorFactory.getValidator();
  7. Set validateResult = validator.validate(t, groups);
  8. if (validateResult.isEmpty()) {
  9. return Collections.emptyMap();
  10. } else {
  11. LinkedHashMap errors = Maps.newLinkedHashMap();
  12. Iterator i$ = validateResult.iterator();
  13. while (i$.hasNext()) {
  14. ConstraintViolation constraintViolation = (ConstraintViolation) i$.next();
  15. errors.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
  16. }
  17. return errors;
  18. }
  19. }
  20. public static Map<String, String> validateForObjects(Object first, Object... others) {
  21. return others != null && others.length != 0 ? validateForList(Lists.asList(first, others)) : validate(first, new Class[0]);
  22. }
  23. public static Map<String, String> validateForList(Collection<?> collection) {
  24. Preconditions.checkNotNull(collection);
  25. Iterator i$ = collection.iterator();
  26. Map errors;
  27. do {
  28. if (!i$.hasNext()) {
  29. return Collections.emptyMap();
  30. }
  31. Object object = i$.next();
  32. errors = validate(object, new Class[0]);
  33. } while (errors.isEmpty());
  34. return errors;
  35. }
  36. }

五、tomcat,mysql配置

  1. # 端口
  2. server.port=8086
  3. spring.profiles.active=pro
  4. spring.application.name=dubbo-producer
  5. # 日志
  6. logging.level.top.happylaishop=DEBUG
  7. logging.level.com.alibaba.nacos.client.naming=ERROR
  8. # jackson
  9. spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
  10. spring.jackson.time-zone=GMT+8
  11. # 数据源
  12. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  13. 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
  14. spring.datasource.username=admin
  15. spring.datasource.password=12345678
  16. # Hikari will use the above plus the following to setup connection pooling
  17. spring.datasource.type=com.zaxxer.hikari.HikariDataSource
  18. spring.datasource.hikari.pool-name=dubbo-producer
  19. spring.datasource.hikari.minimum-idle=1
  20. spring.datasource.hikari.maximum-pool-size=15
  21. spring.datasource.hikari.auto-commit=true
  22. spring.datasource.hikari.idle-timeout=30000
  23. spring.datasource.hikari.max-lifetime=1800000
  24. spring.datasource.hikari.connection-timeout=30000
  25. spring.datasource.hikari.connection-test-query=SELECT 1
  26. # mybatis
  27. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  28. mybatis-plus.mapper-locations=classpath:/mappers/*.xml
  29. #tomcat
  30. #等待队列长度
  31. #server.tomcat.accept-count=1500
  32. #默认值1w
  33. #server.tomcat.max-connections=10000
  34. #最大线程数(4h8g则800)
  35. #server.tomcat.max-threads=1200
  36. #最小线程数
  37. #server.tomcat.min-space-threads=200
  38. # redis
  39. spring.redis.host=${redis.host:127.0.0.1}
  40. spring.redis.port=${redis.port:6379}
  41. spring.redis.lettuce.pool.max-active=${redis.pool.maxActive:300}
  42. spring.redis.lettuce.pool.max-idle=${redis.pool.maxIdle:100}
  43. spring.redis.lettuce.pool.max-wait=${redis.pool.maxWait:1000}
  44. spring.redis.lettuce.pool.min-idle=${redis.minIdle:0}
  45. # spring boot actuator端点启用和暴露
  46. ## * 可以用来表示所有的端点,例如,通过HTTP公开所有的端点
  47. ## * 在YAML中有特殊的含义,所以如果想使用include或者exclude包含所有的端点时要加上双引号
  48. management.endpoints.web.exposure.include=*
  49. management.endpoints.web.exposure.exclude=env,beans
  50. management.endpoints.promethus.enable=true
  51. management.endpoint.health.show-details=always

发表评论

表情:
评论列表 (有 0 条评论,340人围观)

还没有评论,来说两句吧...

相关阅读