RetryService.java 1.61 KB
package cn.com.glsx.notify.modules.service;

import com.glsx.plat.mail.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * springBoot 重试机制测试 service
 *
 * @author Yanglinlong
 * @date 2022/9/19 11:29
 */
@Slf4j
@Service
public class RetryService {

    @Autowired
    private MailUtils mailUtils;

    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 2))
    public void devide(double a, double b) {
        log.info("开始进行除法运算");
        if (b == 0) {
            throw new RuntimeException();
        }
        log.info("{} / {} = {}", a, b, a / b);
    }

    /**
     * 重试发送邮件
     *
     * @param toEmail
     * @param subject
     * @param content
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public void sendMail(String toEmail, String subject, String content) {
        log.info("发送邮件===toEmail:" + toEmail + ",subject:" + subject + ",content:" + content);
        mailUtils.sendTextMail(toEmail, subject, content);
    }


    /**
     * 重试机制次数耗尽,执行补偿机制,可以是邮件通知异常数据
     *
     * @return
     */
    @Recover
    public void recover(Exception e) {
        log.info("has try 3 times ,sendMail fail===" + e.getMessage(), e);
    }
}