[转帖]关于如何在Java项目接口保证幂等性的一点思考_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 2606 | 回复: 0   主题: [转帖]关于如何在Java项目接口保证幂等性的一点思考        上一篇   下一篇 
liuliying930406
注册用户
等级:中校
经验:2027
发帖:210
精华:0
注册:2018-10-9
状态:离线
发送短消息息给liuliying930406 加好友    发送短消息息给liuliying930406 发消息
发表于: IP:您无权察看 2019-2-27 16:07:17 | [全部帖] [楼主帖] 楼主


转自公众号JAVA牛人


什么是接口幂等?

接口幂等就是无论客户端调用服务端接口发起多少次请求,有且只有一次有效。

如何解决幂等问题呢?

1.暴露获取幂等token接口,且在此时存储redis、mysql、本地内存等(可根据具体业务场景选择token存储方式)

@Autowired

private RedissonClient redissonClient;

private String createToken(){

 return UUID.randomUUID().toString().replace("-","");

}

 @GetMapping("/getLdempotentToken")

 public Response<String> getLdempotentToken(){

 RMapCache<String,String> rMapCache = redissonClient.getMapCache(LdempotentAspect.LDEMPOTENT_TONE);

 String token = createToken();

 rMapCache.put(token,token);

 return Response.ok(token);

 }

2.客户端在请求接口前先获取幂等接口,然后在请求接口前写入请求头中.

key value ldempotent_token ba4b441e75f2449792fce5eb0ccfa2ab 3.利用spring aop技术代码需要处理幂等接口。在执行接口之前验证客户端请求头中的幂等token,验证成功则删除token,验证失败则直接返回错误信息.

@Target({ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface Ldempotent {

}

 

@Slf4j

@Component

@Aspect

public class LdempotentAspect {

 public static final String LDEMPOTENT_TONE = "ldempotent_token";

 @Autowired

 private RedissonClient redissonClient;

 @Pointcut("@annotation(com.fast.family.framework.core.redis.ldempotent.Ldempotent)")

 public void pointcut(){}

 @Around("pointcut()")

 public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

 String token = Optional.ofNullable(WebUtils.getRequestHeader(LDEMPOTENT_TONE))

 .orElseThrow(() -> new LdempotentException(ResponseCode.LDEMPOTENT_ERROR.getCode()

 ,ResponseCode.LDEMPOTENT_ERROR.getMsg()));

 RMapCache<String,String> rMapCache = redissonClient.getMapCache(LDEMPOTENT_TONE);

 Optional.ofNullable(rMapCache.get(token))

 .orElseThrow(() -> new LdempotentException(ResponseCode.LDEMPOTENT_ERROR.getCode()

 ,ResponseCode.LDEMPOTENT_ERROR.getMsg()));

 rMapCache.remove(rMapCache.get(token));//token一次有效,所以在验证完后需删除

 return proceedingJoinPoint.proceed();

 }

}

 

那么按照上述步骤则可以保证接口幂等性(这种方式除了可以处理接口幂等,还能处理其他问题吗?哈哈哈哈哈哈)大家思考一下~





赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论