亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring Boot通過Redis實(shí)現(xiàn)防止重復(fù)提交

 更新時(shí)間:2024年06月28日 09:57:22   作者:信仰_273993243  
表單提交是一個(gè)非常常見的功能,如果不加控制,容易因?yàn)橛脩舻恼`操作或網(wǎng)絡(luò)延遲導(dǎo)致同一請求被發(fā)送多次,本文主要介紹了Spring Boot通過Redis實(shí)現(xiàn)防止重復(fù)提交,具有一定的參考價(jià)值,感興趣的可以了解一下

一、什么是冪等。

1、什么是冪等:相同的條極下,執(zhí)行多次結(jié)果拿到的結(jié)果都是一樣的。舉個(gè)例子比如相同的參數(shù)情況,執(zhí)行多次,返回的數(shù)據(jù)都是樣的。那什么情況下要考慮冪等,重復(fù)新增數(shù)據(jù)。

2、解決方案:解決的方式有很多種,本文使用的是本地鎖。

二、實(shí)現(xiàn)思路

1、首先我們要確定多少時(shí)間內(nèi),相同請求參數(shù)視為一次請求,比如2秒內(nèi)相同參數(shù),無論請求多少次都視為一次請求。

2、一次請求的判斷依據(jù)是什么,肯定是相同的形參,請求相同的接口,在1的時(shí)間范圍內(nèi)視為相同的請求。所以我們可以考慮通過參數(shù)生成一個(gè)唯一標(biāo)識(shí),這樣我們根據(jù)唯一標(biāo)識(shí)來判斷。

三、代碼實(shí)現(xiàn)

1、這里我選擇spring的redis來實(shí)現(xiàn),但如果有集群的情況,還是要用集群redis來處理。當(dāng)?shù)谝淮潍@取請求時(shí),根據(jù)請求url、controller層調(diào)用的方法、請求參數(shù)生成MD5值這三個(gè)條件作為依據(jù),將其作為redis的key和value值,并設(shè)置失效時(shí)間,當(dāng)在失效時(shí)間之內(nèi)再次請求時(shí),根據(jù)是否已存在key值來判斷接收還是拒絕請求來實(shí)現(xiàn)攔截。

2、pom.xml依賴

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
	<exclusions>
		<exclusion>
			<groupId>io.lettuce</groupId>
			<artifactId>lettuce-core</artifactId>
		</exclusion>
	</exclusions>
	<version>2.0.6.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.aspectj</groupId>
	<artifactId>aspectjweaver</artifactId>
	<version>1.8.9</version>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.1</version>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
	<version>2.6.0</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.31</version>
</dependency>

3、在application.yml中配置redis

spring:
  redis:
    database: 0
    host: XXX
    port: 6379
    password: XXX
    timeout: 1000
    pool:
      max-active: 1
      max-wait: 10
      max-idle: 2
      min-idle: 50

4、自定義異常類IdempotentException

package com.demo.controller;
public class IdempotentException extends RuntimeException {
	public IdempotentException(String message) {
		super(message);
	}
	
	@Override
	public String getMessage() {
		return super.getMessage();
	}
}

5、自定義注解

package com.demo.controller;
 
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 value();
	// 過期時(shí)間
	long expireMillis();
}

6、自定義切面

package com.demo.controller;
import java.lang.reflect.Method;
import java.util.Objects;
import javax.annotation.Resource;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.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";
 
	@Resource
	private RedisTemplate<String, String> redisTemplate;
 
	//填寫掃描加了自定義注解的類所在的包。
	@Pointcut("@annotation(com.demo.controller.Idempotent)")
	public void executeIdempotent() {
 
	}
 
	@Around("executeIdempotent()")  //環(huán)繞通知
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
		Idempotent idempotent = method.getAnnotation(Idempotent.class);
        //注意Key的生成規(guī)則		
String key = String.format(KEY_TEMPLATE,
				idempotent.value() + "_" + KeyUtil.generate(method, joinPoint.getArgs()));
		String redisRes = redisTemplate
				.execute((RedisCallback<String>) conn -> ((JedisCommands) conn.getNativeConnection()).set(key, key,
						"NX", "PX", idempotent.expireMillis()));
		if (Objects.equals("OK", redisRes)) {
			return joinPoint.proceed();
		} else {
			throw new IdempotentException("Idempotent hits, key=" + key);
		}
	}
}

//注意這里不需要釋放鎖操作,因?yàn)槿绻尫帕耍谙薅〞r(shí)間內(nèi),請求還是會(huì)再進(jìn)來,所以不能釋放鎖操作。

7、Key生成工具類

package com.demo.controller;
 
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
import com.alibaba.fastjson.JSON;
 
public class KeyUtil {
	public static String generate(Method method, Object... args) throws UnsupportedEncodingException {
		StringBuilder sb = new StringBuilder(method.toString());
		for (Object arg : args) {
			sb.append(toString(arg));
		}
		return md5(sb.toString());
	}
 
	private static String toString(Object object) {
		if (object == null) {
			return "null";
		}
		if (object instanceof Number) {
			return object.toString();
		}
		return JSON.toJSONString(object);
	}
 
	public static String md5(String str) {
		StringBuilder buf = new StringBuilder();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte b[] = md.digest();
			int i;
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append(0);
				buf.append(Integer.toHexString(i));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return buf.toString();
	}

8、在Controller中標(biāo)記注解

package com.demo.controller;
 
import javax.annotation.Resource;
 
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class DemoController {
	@Resource
	private RedisTemplate<String, String> redisTemplate;
	
	@PostMapping("/redis")
	@Idempotent(value = "/redis", expireMillis = 5000L)
	public String redis(@RequestBody User user) {
		return "redis access ok:" + user.getUserName() + " " + user.getUserAge();
	}
}

到此這篇關(guān)于Spring Boot通過Redis實(shí)現(xiàn)防止重復(fù)提交的文章就介紹到這了,更多相關(guān)SpringBoot Redis防止重復(fù)提交內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論