Skip to content

Spring

使用注意事项和总结

SpringTask

@Scheduled注解

  • cron 属性:Spring Cron 表达式。
  • fixedDelay 属性:固定执行间隔,单位:毫秒。注意,以调用完成时刻为开始计时时间。
  • fixedRate 属性:固定执行间隔,单位:毫秒。注意,以调用开始时刻为开始计时时间。
  • initialDelay 属性:初始化的定时任务执行延迟,单位:毫秒。
  • zone 属性:解析 Spring Cron 表达式的所属的时区。默认情况下,使用服务器的本地时区。
  • initialDelayString 属性:initialDelay 的字符串形式。
  • fixedDelayString 属性:fixedDelay 的字符串形式。
  • fixedRateString 属性:fixedRate 的字符串形式。
yaml
spring:
  task:
	# Spring Task 调度任务的配置,对应 TaskSchedulingProperties 配置类
	scheduling:
	  thread-name-prefix: pikaqiu-demo- # 线程池的线程名的前缀 默认为 scheduling- 
	  pool:
	  size: 10 # 线程池大小 默认为1,根据自己应用来设置
	  shutdown:
		await-termination: true # 应用关闭时,是否等待定时任务执行完成 默认为 false,建议设置为 true
		await-termination-period: 60 # 等待任务完成的最大时长,单位为秒。默认为 0
spring:
  task:
	# Spring Task 调度任务的配置,对应 TaskSchedulingProperties 配置类
	scheduling:
	  thread-name-prefix: pikaqiu-demo- # 线程池的线程名的前缀 默认为 scheduling- 
	  pool:
	  size: 10 # 线程池大小 默认为1,根据自己应用来设置
	  shutdown:
		await-termination: true # 应用关闭时,是否等待定时任务执行完成 默认为 false,建议设置为 true
		await-termination-period: 60 # 等待任务完成的最大时长,单位为秒。默认为 0

StopWatch

java
public static void test1() throws InterruptedException {
    StopWatch sw = new StopWatch("test");
    try{
        sw.start("task1");
        // do something
        Thread.sleep(100);
        sw.stop();
        sw.start("task2");
        // do something
        Thread.sleep(200);
    }catch(InterruptedException e){
        throws new InterruptedException();
    }finally{
        sw.stop();
        System.out.println(sw.prettyPrint());
        System.out.println(sw.shortSummary());
        System.out.println(sw.getTotalTimeMillis())
    }
}
public static void test1() throws InterruptedException {
    StopWatch sw = new StopWatch("test");
    try{
        sw.start("task1");
        // do something
        Thread.sleep(100);
        sw.stop();
        sw.start("task2");
        // do something
        Thread.sleep(200);
    }catch(InterruptedException e){
        throws new InterruptedException();
    }finally{
        sw.stop();
        System.out.println(sw.prettyPrint());
        System.out.println(sw.shortSummary());
        System.out.println(sw.getTotalTimeMillis())
    }
}

优缺点

  • 优点: spring自带工具类,可直接使用 代码实现简单,使用更简单 统一归纳,展示每项任务耗时与占用总时间的百分比,展示结果直观 性能消耗相对较小,并且最大程度的保证了start与stop之间的时间记录的准确性 可在start时直接指定任务名字,从而更加直观的显示记录结果
  • 缺点: 一个StopWatch实例一次只能开启一个task,不能同时start多个task,并且在该task未stop之前不能start一个新的task,必须在该task stop之后才能开启新的task,若要一次开启多个,需要new不同的StopWatch实例代码侵入式使用,需要改动多处代码

SpringAsync

java
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig extends AsyncConfigurerSupport {

   @Override
   public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
        return new CusAsyncExceptionHandler();
   }

   @Bean("executor")
   public Executor executor(){
        System.out.println("executor 线程启动---");
        ThreadPoolTaskExecutor scheduler = new ThreadPoolTaskExecutor();
        scheduler.setCorePoolSize(5);    //基本线程数量
        scheduler.setQueueCapacity(500);  //队列最大长度
        scheduler.setMaxPoolSize(5);    //最大线程数量
        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        scheduler.setThreadNamePrefix("Myself-Executor-");
        scheduler.setKeepAliveSeconds(30); //允许空闲时间
        scheduler.initialize();
        return scheduler;
   }
}
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig extends AsyncConfigurerSupport {

   @Override
   public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
        return new CusAsyncExceptionHandler();
   }

   @Bean("executor")
   public Executor executor(){
        System.out.println("executor 线程启动---");
        ThreadPoolTaskExecutor scheduler = new ThreadPoolTaskExecutor();
        scheduler.setCorePoolSize(5);    //基本线程数量
        scheduler.setQueueCapacity(500);  //队列最大长度
        scheduler.setMaxPoolSize(5);    //最大线程数量
        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        scheduler.setThreadNamePrefix("Myself-Executor-");
        scheduler.setKeepAliveSeconds(30); //允许空闲时间
        scheduler.initialize();
        return scheduler;
   }
}

SpringRetry

1.依赖

xml
<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>

2.配置类加 @EnableRetry注解,启用重试

3.在方法上添加@Retryable

4.方法调用实例

java
@Service
public class TestRetryService {

    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public int test(int code) throws Exception{
        System.out.println("test被调用,时间:"+LocalTime.now());
        if (code==0){
            throw new Exception("情况不对头!");
        }
        System.out.println("test被调用,情况对头了!");

        return 200;
    }
}
@Service
public class TestRetryService {

    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public int test(int code) throws Exception{
        System.out.println("test被调用,时间:"+LocalTime.now());
        if (code==0){
            throw new Exception("情况不对头!");
        }
        System.out.println("test被调用,情况对头了!");

        return 200;
    }
}

参数含义:

  • value:抛出指定异常才会重试
  • include:和value一样,默认为空,当exclude也为空时,默认所有异常
  • exclude:指定不处理的异常
  • maxAttempts:最大重试次数,默认3次
  • backoff:重试等待策略,默认使用@Backoff@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。

当重试耗尽时,RetryOperations可以将控制传递给另一个回调,即RecoveryCallbackSpring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法。如果不需要回调方法,可以直接不写回调方法,那么实现的效果是,重试次数完了后,如果还是没成功没符合业务判断,就抛出异常。

java
@Recover
public int recover(Exception e, int code){
   System.out.println("回调方法执行!!!!");
   //记日志到数据库 或者调用其余的方法
   return 400;
}
@Recover
public int recover(Exception e, int code){
   System.out.println("回调方法执行!!!!");
   //记日志到数据库 或者调用其余的方法
   return 400;
}

可以看到传参里面写的是 Exception e,这个是作为回调的接头暗号(重试次数用完了,还是失败,我们抛出这个Exception e通知触发这个回调方法)。对于@Recover注解的方法,需要特别注意的是:

  • 方法的返回值必须与@Retryable方法一致
  • 方法的第一个参数,必须是Throwable类型的,建议是与@Retryable配置的异常一致,其他的参数,需要哪个参数,写进去就可以了(@Recover方法中有的)
  • 该回调方法与重试方法写在同一个实现类里面

5.注意事项

  • 由于是基于AOP实现,所以不支持类里自调用方法
  • 如果重试失败需要给@Recover注解的方法做后续处理,那这个重试的方法不能有返回值,只能是void
  • 方法内不能使用try catch,只能往外抛异常
  • @Recover注解来开启重试失败后调用的方法(注意,需跟重处理方法在同一个类中),此注解注释的方法参数一定要是@Retryable抛出的异常,否则无法识别,可以在该方法中进行日志处理。