SpringBoot技术实践-SpringRetry重试框架,来一份全面的面试宝典练练手

private RetryTemplate retryTemplate;

private static int count = 0;

@RequestMapping(“/retry”)

public Object retry() {

try {

count = 0;

retryTemplate.execute((RetryCallback<Void, RuntimeException>) context -> {

// 业务代码

// …

// 模拟抛出异常

++count;

throw new RuntimeException(“抛出异常”);

});

} catch (RuntimeException e) {

System.out.println(“Exception”);

}

return "retry = " + count;

}

}

  1. 访问retry接口,然后观察日志输出

18:27:20.648 - http-nio-8888-exec-1 - open

18:27:20.649 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:20.649 - http-nio-8888-exec-1 - onError

18:27:21.658 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:21.658 - http-nio-8888-exec-1 - onError

18:27:23.670 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:23.670 - http-nio-8888-exec-1 - onError

18:27:27.679 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:27.679 - http-nio-8888-exec-1 - onError

18:27:35.681 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:35.681 - http-nio-8888-exec-1 - onError

18:27:35.681 - http-nio-8888-exec-1 - close

三、EnableRetry

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

  1. @EnableRetry开启重试,在类上指定的时候方法将默认执行,重试三次

  2. 定义service,开启@EnableRetry注解和指定@Retryable,重试可以参考后面一节

import org.springframework.retry.annotation.Retryable;

public interface RetryService {

/**

  • 重试方法调用

*/

@Retryable

void retryServiceCall();

}

import org.springframework.retry.annotation.EnableRetry;

import org.springframework.stereotype.Service;

@EnableRetry

@Service

public class RetryServiceImpl implements RetryService {

@Override

public void retryServiceCall() {

PrintUtil.print(“方法调用…”);

throw new RuntimeException(“手工异常”);

}

}

  1. controller中注入service

@RequestMapping(“/retryAnnotation”)

public Object retryAnnotation() {

retryService.retryServiceCall();

return “retryAnnotation”;

}

  1. 将会默认重试

18:46:48.721 - http-nio-8888-exec-1 - 方法调用…

18:46:49.724 - http-nio-8888-exec-1 - 方法调用…

18:46:50.730 - http-nio-8888-exec-1 - 方法调用…

java.lang.RuntimeException: 手工异常

四、Retryable

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

  1. 用于需要重试的方法上的注解

  2. 有以下几个属性

  • Retryable注解参数

  • value:指定发生的异常进行重试

  • include:和value一样,默认空,当exclude也为空时,所有异常都重试

  • exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试

  • maxAttemps:重试次数,默认3

  • backoff:重试补偿机制,默认没有

  • @Backoff 注解 重试补偿策略

  • 不设置参数时,默认使用FixedBackOffPolicy(指定等待时间),重试等待1000ms

  • 设置delay,使用FixedBackOffPolicy(指定等待设置delay和maxDealy时,重试等待在这两个值之间均态分布)

  • 设置delay、maxDealy、multiplier,使用 ExponentialBackOffPolicy(指数级重试间隔的实现),multiplier即指定延迟倍数,比如delay=5000L,multiplier=2,则第一次重试为5秒,第二次为10秒,第三次为20秒

@Target({ ElementType.METHOD, ElementType.TYPE })

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface Retryable {

/**

  • Retry interceptor bean name to be applied for retryable method. Is mutually

  • exclusive with other attributes.

  • @return the retry interceptor bean name

*/

String interceptor() default “”;

/**

  • Exception types that are retryable. Synonym for includes(). Defaults to empty (and

  • if excludes is also empty all exceptions are retried).

  • @return exception types to retry

*/

Class<? extends Throwable>[] value() default {};

/**

  • Exception types that are retryable. Defaults to empty (and if excludes is also

  • empty all exceptions are retried).

  • @return exception types to retry

*/

Class<? extends Throwable>[] include() default {};

/**

  • Exception types that are not retryable. Defaults to empty (and if includes is also

  • empty all exceptions are retried).

  • If includes is empty but excludes is not, all not excluded exceptions are retried

  • @return exception types not to retry

*/

Class<? extends Throwable>[] exclude() default {};

/**

  • A unique label for statistics reporting. If not provided the caller may choose to

  • ignore it, or provide a default.

  • @return the label for the statistics

*/

String label() default “”;

/**

  • Flag to say that the retry is stateful: i.e. exceptions are re-thrown, but the

  • retry policy is applied with the same policy to subsequent invocations with the

  • same arguments. If false then retryable exceptions are not re-thrown.

  • @return true if retry is stateful, default false

*/

boolean stateful() default false;

/**

  • @return the maximum number of attempts (including the first failure), defaults to 3

*/

int maxAttempts() default 3;

/**

  • @return an expression evaluated to the maximum number of attempts (including the first failure), defaults to 3

  • Overrides {@link #maxAttempts()}.

  • @date 1.2

*/

String maxAttemptsExpression() default “”;

/**

  • Specify the backoff properties for retrying this operation. The default is a

  • simple {@link Backoff} specification with no properties - see it’s documentation

  • for defaults.

  • @return a backoff specification

*/

Backoff backoff() default @Backoff();

/**

  • Specify an expression to be evaluated after the {@code SimpleRetryPolicy.canRetry()}

  • returns true - can be used to conditionally suppress the retry. Only invoked after

  • an exception is thrown. The root object for the evaluation is the last {@code Throwable}.

  • Other beans in the context can be referenced.

  • For example:

  • {@code “message.contains(‘you can retry this’)”}.

  • and

  • {@code “@someBean.shouldRetry(#root)”}.

  • @return the expression.

  • @date 1.2

*/

String exceptionExpression() default “”;

/**

  • Bean names of retry listeners to use instead of default ones defined in Spring context

  • @return retry listeners bean names

*/

String[] listeners() default {};

}

  1. 在需要重试的方法上配置对应的重试次数、重试异常的异常类型、设置回退延迟时间、重试策略、方法监听名称

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface Backoff {

/**

  • Synonym for {@link #delay()}.

  • @return the delay in milliseconds (default 1000)

*/

long value() default 1000;

/**

  • A canonical backoff period. Used as an initial value in the exponential case, and

  • as a minimum value in the uniform case.

  • @return the initial or canonical backoff period in milliseconds (default 1000)

*/

long delay() default 0;

/**

  • The maximimum wait (in milliseconds) between retries. If less than the

  • {@link #delay()} then the default of

  • {@value org.springframework.retry.backoff.ExponentialBackOffPolicy#DEFAULT_MAX_INTERVAL}

  • is applied.

  • @return the maximum delay between retries (default 0 = ignored)

*/

long maxDelay() default 0;

/**

  • If positive, then used as a multiplier for generating the next delay for backoff.

  • @return a multiplier to use to calculate the next backoff delay (default 0 =

  • ignored)

*/

double multiplier() default 0;

/**

  • An expression evaluating to the canonical backoff period. Used as an initial value

  • in the exponential case, and as a minimum value in the uniform case. Overrides

  • {@link #delay()}.

  • @return the initial or canonical backoff period in milliseconds.

  • @date 1.2

*/

String delayExpression() default “”;

/**

  • An expression evaluating to the maximimum wait (in milliseconds) between retries.

  • If less than the {@link #delay()} then the default of

  • {@value org.springframework.retry.backoff.ExponentialBackOffPolicy#DEFAULT_MAX_INTERVAL}

  • is applied. Overrides {@link #maxDelay()}

  • @return the maximum delay between retries (default 0 = ignored)

  • @date 1.2

*/

String maxDelayExpression() default “”;

/**

  • Evaluates to a vaule used as a multiplier for generating the next delay for

  • backoff. Overrides {@link #multiplier()}.

  • @return a multiplier expression to use to calculate the next backoff delay (default

  • 0 = ignored)

  • @date 1.2

*/

String multiplierExpression() default “”;

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
img

最后

由于篇幅原因,就不多做展示了

学提升又不知道该从何学起的朋友,同时减轻大家的负担。**
[外链图片转存中…(img-ReU4I5XE-1711155957136)]
[外链图片转存中…(img-0SYNCcP9-1711155957137)]
[外链图片转存中…(img-804iwH34-1711155957137)]

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
[外链图片转存中…(img-jkP0Ddxm-1711155957138)]

最后

[外链图片转存中…(img-FD4tClTA-1711155957138)]

[外链图片转存中…(img-VR6pM964-1711155957139)]

[外链图片转存中…(img-98GLDgdz-1711155957140)]

[外链图片转存中…(img-9TvVhxTu-1711155957140)]

[外链图片转存中…(img-rzXIqtES-1711155957141)]

[外链图片转存中…(img-q6TdQOop-1711155957141)]

由于篇幅原因,就不多做展示了

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

  • 29
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的 Spring Boot 实战项目,用于管理用户信息: 1. 创建一个基础的 Spring Boot 项目,引入以下依赖: ```xml <!-- Spring Boot Web 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot JPA 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- H2 数据库依赖 --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> ``` 2. 创建一个实体类 User,包含 id、name、age 三个属性: ```java @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 3. 创建一个 UserRepository 接口,继承 JpaRepository,用于操作用户数据: ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 4. 创建一个 UserController 类,用于处理用户信息的增删改查: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("") public List<User> list() { return userRepository.findAll(); } @PostMapping("") public User create(@RequestBody User user) { return userRepository.save(user); } @GetMapping("/{id}") public User get(@PathVariable Long id) { return userRepository.findById(id).orElse(null); } @PutMapping("/{id}") public User update(@PathVariable Long id, @RequestBody User user) { user.setId(id); return userRepository.save(user); } @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { userRepository.deleteById(id); } } ``` 5. 启动项目,访问 http://localhost:8080/users 即可查看用户列表,使用 POST、PUT、DELETE 方法操作用户信息。 以上就是一个简单的 Spring Boot 实战项目,可以通过这个项目练习 Spring Boot 的基本使用和 RESTful API 的实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值