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

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;

	/**
	 * 

* 获取客户端的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 *

* * @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("请求成功");
    }

你可能感兴趣的:(Redis)