springboot实现幂等性
spring boot 实现幂等性
背景
在分布式服务中,业务在⾼并发的情况下会消费者出现多次请求的情况.这个时候如果执⾏插⼊的业务操作,则数据库中出现多条数据.造成脏数据的产⽣.⽽且也是对资源的浪费.
此时我们需要做的就是阻⽌多页业务的处理操作.
执⾏⽅案
实现接⼝的幂等性,让请求只成功⼀次.这⾥需要保存⼀个唯⼀标⽰,在下⼀个请求执⾏时获取标⽰如果重复提交则阻⽌执⾏.
代码实现
创建⼀个⾃定义异常,阻⽌接⼝的下⼀步执⾏
/**
* ⾃定义异常类
*/
public class IdempotentException extends RuntimeException{
private static final long serialVersionUID = 1L;
public IdempotentException(String message){
super(message);
}
@Override
public String getMessage() {
Message();
}
}
⽣成key值⼯具类
import flect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.alibaba.fastjson.JSON;
/**
* IdempotentKeyUtil
* ⽣成key值⼯具类
*/
public class IdempotentKeyUtil {
/
**
* 对接⼝的参数进⾏处理⽣成固定key
* @param method
* @param args
* @return
*/
public static String generate(Method args) {
StringBuilder stringBuilder = new String());
for (Object arg : args) {
stringBuilder.append(toStrinhg(arg));
}
/
/进⾏md5等长加密
return String());
}
}
/**
* 使⽤jsonObject对数据进⾏toString,(保持数据⼀致性)
* @param object
* @return
*/
public static String toStrinhg(Object obj){
if( obj == null ){
return "-";
}
JSONString(obj);
}
/**
* 对数据进⾏MD5等长加密
* @param str
* @return
*/
public static String md5(String str){
StringBuilder stringBuilder = new StringBuilder();
try {
//选择MD5作为加密⽅式
MessageDigest mDigest = Instance("MD5"); mDigest.Bytes());
byte b[] = mDigest.digest();
int j = 0;
for (int i = 0,max = b.length; i < max; i++) {
j = b[i];
if(j < 0 ){
i += 256;
}else if(j < 16){
stringBuilder.append(0);
}
stringBuilder.HexString(j));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String();
}
}
⾃定义注解
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ⾃定义注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Idempotent{
/
/注解⾃定义redis的key的⼀部分
String key();
//过期时间
long expirMillis();
}
AOP对我们⾃定义注解进⾏拦截处理
import flect.Method;
import flect.Method;
import java.util.Objects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.flect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dition.ConditionalOnClass;
import org.RedisCallback;
import org.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCommands;
/**
* ⾃定义切点
*/
@Component
@Aspect
@ConditionalOnClass(RedisTemplate.class)
public class IdempotentAspect{
private static final String KEY_TEMPLATE = "idempotent_%S";
@Autowired
private RedisTemplate<String,String> redisTemplate;
/**
* 切点(⾃定义注解)
*/
springboot aop
@Pointcut("@annotation(Idempotent)")
public void executeIdempotent(){
}
/**
* 切点业务
*
* @throws Throwable
*/
@Around("executeIdempotent()")
public Object arountd(ProceedingJoinPoint jPoint) throws Throwable {
//获取当前⽅法信息
Method method = ((Signature()).getMethod();
//获取注解
Idempotent idempotent = Annotation(Idempotent.class);
//⽣成Key
String key = String.format(KEY_TEMPLATE,idempotent.key()+"_"+ate(method, Args()));
//segmentfault/a/1190000002870317 -- JedisCommands接⼝的分析
//nxxx的值只能取NX或者XX,如果取NX,则只有当key不存在是才进⾏set,如果取XX,则只有当key已经存在时才进⾏set
//expx expx的值只能取EX或者PX,代表数据过期时间的单位,EX代表秒,PX代表毫秒
// key value nxxx(set规则) expx(取值规则) time(过期时间)
String redisRes = ute((RedisCallback<String>)conn ->((NativeConnection()).set(key, key,"NX","EX",pirMillis()));
// Jedis jedis = new Jedis("127.0.0.1",6379);
// jedis.auth("xuzz");
// jedis.select(0);
// String redisRes = jedis.set(key, key,"NX","EX",pirMillis());
if(Objects.equals("OK", redisRes)){
return jPoint.proceed();
}else{
//throw new IdempotentException("sorry!! Interface duplicates requests, violating idempotency.");
return null;
}
}
}
}
service 接⼝
import com.alibaba.fastjson.JSONObject;
/**
* TestService
*/
public interface TestService {
/**
* 数据测试
*/
public void print(JSONObject params);
}
service 实现类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import Idempotent;
import org.springframework.stereotype.Service;
/**
* TestServiceImpl
*/
@Service
public class TestServiceImpl implements TestService {
/**
*
*/
@Idempotent(key = "ller.IdempotentController",expirMillis = 100) @Override
public void print(JSONObject params) {
}
}
controller
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* IdempotentController
*/
@RestController
public class IdempotentController {
@Autowired
private TestService testService;
/**
* 测试push
*/
//@Idempotent(key = "ller.IdempotentController",expirMillis = 100)
@PostMapping("/push/test")
public String pushTest(@RequestBody JSONObject params){
for (int i = 0; i < 5; i++) {
new Thread(()->{
try {
testService.print(params);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
JSONString(params);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.idempotent</groupId>
<artifactId>idempotent-dome</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> -->
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论