redis 计数器 防止表单重复提交

Redis 专栏收录该内容
3 篇文章 0 订阅

redis 计数器用途

社交产品业务里有很多统计计数的功能,比如:

  • 用户: 总点赞数,关注数,粉丝数
  • 帖子: 点赞数,评论数,热度
  • 消息: 已读,未读,红点消息数
  • 话题: 阅读数,帖子数,收藏数

统计计数的特点

  • 实时性要求高
  • 写的频率很高
  • 写的性能对MySQL是一个挑战
  • 可以采用redis来优化高频率写入的性能要求。

实现防止表单重复提交

NoRepeatSubmit


import java.lang.annotation.*;

/**
 * @program: newpay
 * @description: 防止重复提交注释
 * @author: xpx
 * @create: 2020-07-03 15:06
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoRepeatSubmit {

}

SubmitAspect


import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.concurrent.TimeUnit;

/**
 * @program: newpay
 * @description: 防止重复提交代码实现
 * @author: xpx
 * @create: 2020-07-03 15:06
 */
@Aspect
@Configuration
@Slf4j
public class SubmitAspect {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private RedisTemplate redisTemplate;

    @Around("execution(public * *(..)) && @annotation(com.runwu.newpay.member.client.util.NoRepeatSubmit)")
    public Object interceptor(ProceedingJoinPoint point) throws Throwable {
		//获取提交参数
        Object paramsObj = point.getArgs()[0];
		//获取建值
        String redisKey = this.getCacheKey(paramsObj);
		//加入缓存中,每次执行+1
        long count = redisTemplate.opsForValue().increment(redisKey, 1);
		//count == 说明是第一次提交
        if (count == 1) {
        	//设置缓存过期时间 2 秒 ,两秒内不弄重复提交
            redisTemplate.expire(redisKey, 2, TimeUnit.SECONDS);
        }

		//如果在缓存没失效的的情况下,进行多次请求,则返回请求失败信息
        if (count > 1) {
       		//这里大家
            return Response.fail("请勿重复提交");
        }

		//执行目标方法
        return point.proceed();
    }

    /**
     * 加上用户的唯一标识
     * 如果不加上用户的唯一标识,就会出现两个不同用户,提交相同的数据,请求失败的问题
     * 思路:登陆用户的唯一标识(ID或者会员号)+ 请求的IP(客户端IP) + 请求参数
     * MD5加密:key过长显得没那么像key,所以我这就加密了一下,哈哈
     */
    private String getCacheKey(Object paramsObj) {
        String result = "";
        try {
            //获取当前登陆用户的唯一标识
            JWTUser user = (JWTUser) SecurityUtils.getSubject().getPrincipal();
            Object unique = user.getUser().getId();
            if (unique == null) {
                LoginMember member = (LoginMember) user.getUser();
                unique = member.getMemberNo();
            }

            //获取请求IP地址
            String ip = IpHelper.getIpAddr(httpServletRequest);
            unique = unique == null ? "" : unique.toString();

            // 唯一标识+ip+参数,组成请求唯一键,防止参数重复提交
            String key = unique + ip + JsonUtil.toJsonNotNull(paramsObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(key.getBytes());

            //加密成16位
            result = new BigInteger(1, md.digest()).toString(16);

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(Response.fail("请求参数获取唯一标识异常"));
        }

        return result;
    }

}

IpHelper


import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Logger;


public class IpHelper {

	private static final Logger logger = Logger.getLogger("IpHelper");

	private static String LOCAL_IP_STAR_STR = "192.168.";

	static {
		String ip = null;
		String hostName = null;
		try {
			hostName = InetAddress.getLocalHost().getHostName();
			InetAddress ipAddr[] = InetAddress.getAllByName(hostName);
			for (int i = 0; i < ipAddr.length; i++) {
				ip = ipAddr[i].getHostAddress();
				if (ip.startsWith(LOCAL_IP_STAR_STR)) {
					break;
				}
			}
			if (ip == null) {
				ip = ipAddr[0].getHostAddress();
			}

		} catch (UnknownHostException e) {
			logger.severe("IpHelper error.");
			e.printStackTrace();
		}

		LOCAL_IP = ip;
		HOST_NAME = hostName;

	}

	/** 系统的本地IP地址 */
	public static final String LOCAL_IP;

	/** 系统的本地服务器名 */
	public static final String HOST_NAME;

	/**
	 * <p>
	 *  获取客户端的IP地址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的。
	 *  但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了,如果通过了多级反向代理的话,
	 *  X-Forwarded-For的值并不止一个,而是一串IP值, 究竟哪个才是真正的用户端的真实IP呢?
	 *  答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
	 *  例如:X-Forwarded-For:192.168.1.110, 192.168.1.120,
	 *  192.168.1.130, 192.168.1.100 用户真实IP为: 192.168.1.110
	 *  </p>
	 *  
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String fromSource = "X-Real-IP";  
	    String ip = request.getHeader("X-Real-IP");  
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("X-Forwarded-For");  
	        fromSource = "X-Forwarded-For";  
	    }  
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	        fromSource = "Proxy-Client-IP";  
	    }  
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	        fromSource = "WL-Proxy-Client-IP";  
	    }  
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	        fromSource = "request.getRemoteAddr";  
	    }  
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1")) {
				/** 根据网卡取本机配置的IP */
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
					ip = inet.getHostAddress();
				} catch (UnknownHostException e) {
					logger.severe("IpHelper error." + e.toString());
				}
			}
		}
		/**
		 * 对于通过多个代理的情况, 第一个IP为客户端真实IP,多个IP按照','分割 "***.***.***.***".length() =
		 * 15
		 */
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}
}

test

    @Path("/testSubmit")
    @POST
    @Api(value = "测试防止重复提交", desc = "测试防止重复提交")
    @Consumes(MediaType.APPLICATION_JSON)
    @NoRepeatSubmit
    public Response testSubmit(SncodeAddRequest request) {
        log.info("request:{}", JSONUtil.toJsonStr(request));
        return Response.ok("请求成功");
    }
  • 0
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

<h4 style="font-weight:500;font-size:1.5rem;font-family:'PingFang SC', 'Hiragino Sans GB', Arial, 'Microsoft YaHei', Verdana, Roboto, Noto, 'Helvetica Neue', sans-serif;color:#222226;background-color:#ffffff;text-align:center;"> <span style="font-size:14px;">期末</span><span style="font-size:14px;background-color:#fbeeb8;">考点</span><span style="font-size:14px;">都对应</span><span style="font-size:14px;background-color:#fbeeb8;">详解视频</span><span style="font-size:14px;">,</span><span style="font-size:14px;"><span style="color:#e03e2d;">基础阶段</span></span><span style="font-size:14px;">内容全面,语言通俗易懂(翻译书中的语言为</span><span style="font-size:14px;background-color:#fbeeb8;">人话)</span><span style="font-size:14px;">,</span> </h4> <h4 style="font-weight:500;font-size:1.5rem;font-family:'PingFang SC', 'Hiragino Sans GB', Arial, 'Microsoft YaHei', Verdana, Roboto, Noto, 'Helvetica Neue', sans-serif;color:#222226;background-color:#ffffff;text-align:center;"> <span style="font-size:14px;">老师精心研究</span><span style="font-size:14px;background-color:#fbeeb8;">百份</span><span style="font-size:14px;">考卷,总结每一个考点,同时结合你肯定可以听懂的骚话,</span> </h4> <h4 style="font-weight:500;font-size:1.5rem;font-family:'PingFang SC', 'Hiragino Sans GB', Arial, 'Microsoft YaHei', Verdana, Roboto, Noto, 'Helvetica Neue', sans-serif;color:#222226;background-color:#ffffff;text-align:center;"> <span style="font-size:14px;background-color:#fbeeb8;">扫清你的数据库系统盲区</span> </h4> <h4 style="font-weight:500;font-size:1.5rem;font-family:'PingFang SC', 'Hiragino Sans GB', Arial, 'Microsoft YaHei', Verdana, Roboto, Noto, 'Helvetica Neue', sans-serif;color:#222226;background-color:#ffffff;text-align:center;"> <span style="font-size:14px;"><span style="color:#e03e2d;">真题阶段</span></span><span style="font-size:14px;">为你提供</span><span style="font-size:14px;background-color:#fbeeb8;">解题思路</span><span style="font-size:14px;">,培养你的</span><span style="font-size:14px;background-color:#fbeeb8;">解题思维</span><span style="font-size:14px;">,同时</span><span style="font-size:14px;background-color:#fbeeb8;">点明考点</span><span style="font-size:14px;">,结合文档进行重点解读,加深你的印象.</span> </h4> <h4 style="font-weight:500;font-size:1.5rem;font-family:'PingFang SC', 'Hiragino Sans GB', Arial, 'Microsoft YaHei', Verdana, Roboto, Noto, 'Helvetica Neue', sans-serif;color:#222226;background-color:#ffffff;text-align:center;"> <span style="font-size:14px;color:#3598db;">只为你的高分,我们交个朋友!让每位学生都可以学的起!!</span> </h4> <p> <span style="font-size:14px;color:#3598db;"><img src="https://img-bss.csdnimg.cn/202103040423318088.png" alt="" width="788" height="450" /></span> </p>
©️2021 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值