幂等库:Jdempotent


幂等库:Jdempotent

这个 Jdempotent-spring-boot-starter 的目标

用法

  1. 首先需要给 pom.xml 添加一个依赖

对于 Redis:


    com.trendyol
    Jdempotent-spring-boot-redis-starter
    1.1.0

对于Couchbase


    com.trendyol
    Jdempotent-spring-boot-couchbase-starter
    1.1.0

  1. @IdempotentResource您应该为要创建幂等资源、侦听器等的方法添加注释。
@IdempotentResource(cachePrefix = "WelcomingListener")@KafkaListener(topics = "trendyol.mail.welcome", groupId = "group_id")public void consumeMessage(@IdempotentRequestPayload String emailAdress) {
    SendEmailRequest request = SendEmailRequest.builder()
            .email(message)
            .subject(subject)
            .build();

    try {
        mailSenderService.sendMail(request);
    } catch (MessagingException e) {
        logger.error("MailSenderService.sendEmail() throw exception {} event: {} ", e, emailAdress);

        // Throwing any exception is enough to delete from redis. When successful, it will not be deleted from redis and will be idempotent.
        throw new RetryIdempotentRequestException(e);
    }
}

如果想要在您的有效负载中使用 idempotencyId。将@JdempotentId生成的幂等标识符放入带注释的字段中的注释。可以认为是jpa中的@Id注解。

public class IdempotentPaylaod {
   @JdempotentId
   private String jdempotentId;
   private Object data;
}

您可能希望以不同方式处理字段的名称以确保幂等性。只需使用@JdempotentProperty 注解需要获取不同的字段名称并生成受jackson启发的哈希(@JsonProperty 注解)

public class IdempotentPaylaod {
   @JdempotentProperty("userId")
   private String customerId;
   private Object data;
}
  1. 如果要处理自定义错误情况,则需要ErrorConditionalCallback像以下示例一样实现:
@Component
public class AspectConditionalCallback implements ErrorConditionalCallback {

    @Override
    public boolean onErrorCondition(Object response) {
        return response == IdempotentStateEnum.ERROR;
    }
   
    public RuntimeException onErrorCustomException() {
        return new RuntimeException("Status cannot be error");
    }

}
  1. 让我们进行配置:

对于 redis 配置:

jdempotent:
  enable: true
  cache:
    redis:
      database: 1
      password: "password"
      sentinelHostList: 192.168.0.1,192.168.0.2,192.168.0.3
      sentinelPort: "26379"
      sentinelMasterName: "admin"
      expirationTimeHour: 2
      dialTimeoutSecond: 3
      readTimeoutSecond: 3
      writeTimeoutSecond: 3
      maxRetryCount: 3
      expireTimeoutHour: 3

对于Couchbase配置:

jdempotent:
  enable: true
  cryptography:
    algorithm: MD5
  cache:
    couchbase:
      connection-string: XXXXXXXX
      password: XXXXXXXX
      username: XXXXXXXX
      bucket-name: XXXXXXXX
      connect-timeout: 100000
      query-timeout: 20000
      kv-timeout: 3000
请注意,如果需要,您可以轻松禁用 Jdempotent。例如,假设您没有断路器并且您的 Redis 已关闭。在这种情况下,您可以使用以下配置禁用 Jdempotent:
@SpringBootApplication(
      exclude = { RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class }
)

表现

如下图所示,Jdempotent 最消耗 cpu 的部分是获取 Redis 连接,因此我们无需担心与性能相关的问题。

幂等库:Jdempotent

关于该库,可以在gh上搜索

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章