java接口防止重复提交请求的自定义注解实现

1 模块目录

在这里插入图片描述

2 自定义注解

package com.hfwy.common.idempotent.annotation;

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

/**
 * 自定义注解防止表单重复提交
 *
 * @author Lion Li
 */
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit {

	/**
	 * 间隔时间(ms),小于此时间视为重复提交
	 */
	int interval() default 5000;

	TimeUnit timeUnit() default TimeUnit.MILLISECONDS;

	/**
	 * 提示消息 支持国际化 格式为 {code}
	 */
	String message() default "{repeat.submit.message}";

}

3 切面类

package com.hfwy.common.idempotent.aspectj;

import cn.dev33.satoken.SaManager;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.hfwy.common.core.constant.Constants;
import com.hfwy.common.core.domain.R;
import com.hfwy.common.core.exception.ServiceException;
import com.hfwy.common.core.utils.JsonUtils;
import com.hfwy.common.core.utils.MessageUtils;
import com.hfwy.common.core.utils.ServletUtils;
import com.hfwy.common.core.utils.StringUtils;
import com.hfwy.common.idempotent.annotation.RepeatSubmit;
import com.hfwy.common.redis.utils.RedisUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Collection;
import java.util.Map;

/**
 * 防止重复提交(参考美团GTIS防重系统)
 *
 * @author Lion Li
 */
@Aspect
public class RepeatSubmitAspect {

	private static final ThreadLocal<String> KEY_CACHE = new ThreadLocal<>();

	@Before("@annotation(repeatSubmit)")
	public void doBefore(JoinPoint point, RepeatSubmit repeatSubmit) throws Throwable {
		// 如果注解不为0 则使用注解数值
		long interval = repeatSubmit.timeUnit().toMillis(repeatSubmit.interval());

		if (interval < 1000) {
			throw new ServiceException("重复提交间隔时间不能小于'1'秒");
		}
		HttpServletRequest request = ServletUtils.getRequest();
		String nowParams = argsArrayToString(point.getArgs());

		// 请求地址(作为存放cache的key值)
		String url = request.getRequestURI();

		// 唯一值(没有消息头则使用请求地址)
		String submitKey = StringUtils.trimToEmpty(request.getHeader(SaManager.getConfig().getTokenName()));

		submitKey = SecureUtil.md5(submitKey + ":" + nowParams);
		// 唯一标识(指定key + url + 消息头)
		String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + url + submitKey;
		String key = RedisUtils.getCacheObject(cacheRepeatKey);
		if (key == null) {
			RedisUtils.setCacheObject(cacheRepeatKey, "", Duration.ofMillis(interval));
			KEY_CACHE.set(cacheRepeatKey);
		}
		else {
			String message = repeatSubmit.message();
			if (StringUtils.startsWith(message, "{") && StringUtils.endsWith(message, "}")) {
				message = MessageUtils.message(StringUtils.substring(message, 1, message.length() - 1));
			}
			throw new ServiceException(message);
		}
	}

	/**
	 * 处理完请求后执行
	 * @param joinPoint 切点
	 */
	@AfterReturning(pointcut = "@annotation(repeatSubmit)", returning = "jsonResult")
	public void doAfterReturning(JoinPoint joinPoint, RepeatSubmit repeatSubmit, Object jsonResult) {
		if (jsonResult instanceof R) {
			try {
				R<?> r = (R<?>) jsonResult;
				// 成功则不删除redis数据 保证在有效时间内无法重复提交
				if (r.getCode() == R.SUCCESS) {
					return;
				}
				RedisUtils.deleteObject(KEY_CACHE.get());
			}
			finally {
				KEY_CACHE.remove();
			}
		}
	}

	/**
	 * 拦截异常操作
	 * @param joinPoint 切点
	 * @param e 异常
	 */
	@AfterThrowing(value = "@annotation(repeatSubmit)", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, RepeatSubmit repeatSubmit, Exception e) {
		RedisUtils.deleteObject(KEY_CACHE.get());
		KEY_CACHE.remove();
	}

	/**
	 * 参数拼装
	 */
	private String argsArrayToString(Object[] paramsArray) {
		StringBuilder params = new StringBuilder();
		if (paramsArray != null && paramsArray.length > 0) {
			for (Object o : paramsArray) {
				if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
					try {
						params.append(JsonUtils.toJsonString(o)).append(" ");
					}
					catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return params.toString().trim();
	}

	/**
	 * 判断是否需要过滤的对象。
	 * @param o 对象信息。
	 * @return 如果是需要过滤的对象,则返回true;否则返回false。
	 */
	@SuppressWarnings("rawtypes")
	public boolean isFilterObject(final Object o) {
		Class<?> clazz = o.getClass();
		if (clazz.isArray()) {
			return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
		}
		else if (Collection.class.isAssignableFrom(clazz)) {
			Collection collection = (Collection) o;
			for (Object value : collection) {
				return value instanceof MultipartFile;
			}
		}
		else if (Map.class.isAssignableFrom(clazz)) {
			Map map = (Map) o;
			for (Object value : map.entrySet()) {
				Map.Entry entry = (Map.Entry) value;
				return entry.getValue() instanceof MultipartFile;
			}
		}
		return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
				|| o instanceof BindingResult;
	}

}

4 功能配置类

package com.hfwy.common.idempotent.config;

import com.hfwy.common.idempotent.aspectj.RepeatSubmitAspect;
import com.hfwy.common.redis.config.RedisConfiguration;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

/**
 * 幂等功能配置
 *
 * @author Lion Li
 */
@AutoConfiguration(after = RedisConfiguration.class)
public class IdempotentAutoConfiguration {

	@Bean
	public RepeatSubmitAspect repeatSubmitAspect() {
		return new RepeatSubmitAspect();
	}

}

5 配置文件 org.springframework.boot.autoconfigure.AutoConfiguration.imports

com.hfwy.common.idempotent.config.IdempotentAutoConfiguration

6 pom.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>com.hfwy</groupId>
        <artifactId>energy-electrolysis-common</artifactId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>energy-electrolysis-common-idempotent</artifactId>

    <description>
        energy-electrolysis-common-idempotent 幂等功能
    </description>

	<dependencies>

        <!-- SpringBoot core -->
        <dependency>
            <groupId>com.hfwy</groupId>
            <artifactId>energy-electrolysis-common-core</artifactId>
        </dependency>

        <dependency>
            <groupId>com.hfwy</groupId>
            <artifactId>energy-electrolysis-common-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.dev33</groupId>
            <artifactId>sa-token-core</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-crypto</artifactId>
        </dependency>

    </dependencies>
</project>

7 使用方法

在这里插入图片描述

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java定义注解可以用于实现接口的幂等操作。所谓接口的幂等,就是同一个请求多次执行也不会产生重复的副作用。 要实现接口的幂等,可以通过以下步骤: 1. 定义一个自定义注解,例如@Idempotent,用于标识接口方法的幂等性。 ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Idempotent { } ``` 2. 在接口方法上使用@Idempotent注解,表示该接口方法是幂等的。 ```java public interface MyService { @Idempotent void myMethod(); } ``` 3. 在实现类中,通过AOP的方式实现接口方法的幂等逻辑。可以使用AspectJ或Spring AOP等框架来实现。 ```java @Component @Aspect public class IdempotentAspect { @Autowired private IdempotentService idempotentService; @Around("@annotation(com.example.Idempotent)") public void checkIdempotent(ProceedingJoinPoint joinPoint) throws Throwable { // 获取方法参数,生成幂等key String idempotentKey = generateIdempotentKey(joinPoint.getArgs()); // 判断该key是否已经执行过,如果执行过则直接返回 if (idempotentService.isExecuted(idempotentKey)) { return; } // 执行方法体 joinPoint.proceed(); // 标记该key已经执行过 idempotentService.markExecuted(idempotentKey); } // 生成幂等key的逻辑 private String generateIdempotentKey(Object[] args) { // 根据接口方法的参数生成唯一标识,例如将参数拼接成字符串 return StringUtils.join(args); } } ``` 通过以上步骤,我们就可以实现接口方法的幂等性。在执行接口方法之前,会先判断该方法是否已经执行过,如果已执行过,则直接返回,避免重复执行产生副作用。同时,通过自定义注解@Idempotent的标识,可以简化幂等逻辑的实现和管理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值