自定义注解的实现

本文介绍了如何在Spring Boot应用中通过@AccessLimit注解实现方法级别的限流,并配合Redis进行会话计数。同时,展示了如何利用AOP和@Constraint注解实现数据的唯一性验证。
摘要由CSDN通过智能技术生成

1,web应用中实现限流注解,利用拦截器实现

package com.daojiao.seckill.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * <p>
 * 流量限制的拦截器
 *
 * </p>
 *
 * @author gaojiaxue 2021/10/21
 */
@Target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessLimit {
	int seconds() default 5;
	int count() default 5;
	boolean isLogin() default true;

}
package com.daojiao.seckill.config;

import com.daojiao.seckill.constant.ResBeanEnum;
import com.daojiao.seckill.pojo.User;
import com.daojiao.seckill.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 拦截对应的自定义的拦截器注解的方法
 * </p>
 *
 * @author gaojiaxue 2021/10/21
 */
@Component
@AllArgsConstructor
public class AccessLimitInterceptor implements HandlerInterceptor {



	private  UserService userService;
	private  RedisTemplate redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(handler instanceof HandlerMethod){
			HandlerMethod method=	((HandlerMethod) handler);
			AccessLimit methodAnnotation = method.getMethodAnnotation(AccessLimit.class);
			if(methodAnnotation==null){
				return true;
			}

			User user=getUser(request,response);
			UserContext.setContext(user);
			int seconds=methodAnnotation.seconds();
			int maxCount=methodAnnotation.count();
			boolean login = methodAnnotation.isLogin();
			if(login){
				if(user==null){
					render(response,ResBeanEnum.SESSION_ERROR);
					return false;
				}
				String uri=request.getRequestURI();
				ValueOperations valueOperations = redisTemplate.opsForValue();
				//从redis中获取该对象是否已经登录  对应的值是浏览的次数
				Integer count = (Integer)valueOperations.get(uri + ":" + user.getUserid());
				if(count==null){
					valueOperations.set(uri + ":" + user.getUserid(),1,seconds, TimeUnit.SECONDS);
				}else if(count<maxCount){
					valueOperations.increment(uri + ":" + user.getUserid());
				}else {
					//访问次数过多
					render(response,ResBeanEnum.SESSION_ERROR);
					return false;
				}
			}

		}
		return true;
	}

	/**
	 * 获取当前用户
	 * @param request
	 * @param response
	 */
	private User getUser(HttpServletRequest request, HttpServletResponse response) {
		Cookie tokenc = getCookie(request,"token");
		if(tokenc==null){
			return null;
		}
		String token=tokenc.toString();
		if(token==null||token==""){
			return null;
		}
		System.out.println(userService);
		return userService.getUserByCookie(token,request,response);
	}

	/**
	 * 构建返回对象
	 * @param response
	 * @param sessionError
	 */
	private void render(HttpServletResponse response, ResBeanEnum sessionError) throws IOException {
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=response.getWriter();
		out.write(new ObjectMapper().writeValueAsString(response));
		out.flush();
		out.close();
	}

	/**
	 *
	 * @desc 根据Cookie名称得到Cookie对象,不存在该对象则返回Null
	 * @param request
	 * @param name
	 */
	public  Cookie getCookie(HttpServletRequest request, String name) {

		Cookie[] cookies = request.getCookies();
		if (cookies == null || name == null || name.length() == 0){
			return null;
		}
		Cookie cookie = null;
		for (int i = 0; i < cookies.length; i++) {
			if (!cookies[i].getName().equals(name)){
				continue;
			}
			cookie = cookies[i];
			if (request.getServerName().equals(cookie.getDomain())){
				break;
			}
		}
		return cookie;
	}

}

2,利用@Constraint实现

package com.daojiao.seckill.utils;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * <p>
 *  用@Constraint实现
 * 自定义的唯一性注解
 * </p>
 *
 * @author gaojiaxue 2021/10/11
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
		validatedBy = { queueValidUtil.class}
)
public @interface IsQueue {

	/**
	 * 定义是否必填
	 * @return
	 */
	boolean required() default true;

	String message() default "唯一性验证错误";

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};


}
package com.daojiao.seckill.utils;

import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * <p>
 * 唯一性验证 的注解
 * </p>
 *
 * @author gaojiaxue 2021/10/11
 */
@Component
public class queueValidUtil implements ConstraintValidator<IsQueue,String> {
	private boolean required=false;

	@Override
	public void initialize(IsQueue constraintAnnotation) {
		required=constraintAnnotation.required();
	}

	@Override
	public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
		//TODO 唯一性验证的处理
		return false;
	}
}

3,利用AOP方式实现(此方法不太使用于要用到httprequest)

package tech.codemine.nullcheck.annotation;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Inherited
public @interface NotNull {

}
package tech.codemine.nullcheck.aspect;

import javafx.util.Pair;
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.stereotype.Component;
import tech.codemine.nullcheck.annotation.NotNull;
import tech.codemine.nullcheck.exception.ParameterIsNullException;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 @Auther: wangzhen25
 @Date: 2018/11/20 16:51
 @Description:
 */
@Aspect
@Component
public class NullCheckAspect {
    
    // 在这里定义切点,切点为我们之前设置的注解@CheckAllNotNull
    @Pointcut("@annotation(tech.codemine.nullcheck.annotation.CheckAllNotNull)")
    public void checkAllNotNullPointcut() {
    }

    // 在这里定义切点,切点为我们之前设置的注解@CheckNotNull
    @Pointcut("@annotation(tech.codemine.nullcheck.annotation.CheckNotNull)")
    public void checkNotNullPointcut() {
    }

    // 在这里定义@CheckAllNotNull的增强方法
    @Around("checkAllNotNullPointcut()")
    public Object methodsAnnotatedWithCheckAllNotNull(ProceedingJoinPoint joinPoint) throws Throwable {
        // 首先获取方法的签名,joinPoint中有相应的签名信息
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        // 通过方法的签名可以获取方法本身
        Method method = signature.getMethod();
        // 通过joinPoint获取方法的实际参数的值
        Object[] args = joinPoint.getArgs();
        // 对参数的值进行遍历判断,如果为null则抛出异常
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            if(arg == null)
                throw new ParameterIsNullException(method, i + 1);
        }
        // 最后如果校验通过则调用proceed方法进行方法的实际执行
        return joinPoint.proceed();
    }

    // 在这里定义@CheckNotNull的增强方法
    @Around("checkNotNullPointcut()")
    public Object methodsAnnotatedWithCheckNotNull(ProceedingJoinPoint joinPoint) throws Throwable {
        // 首先获取方法的签名,joinPoint中有相应的签名信息
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        // 通过方法的签名可以获取方法本身
        Method method = signature.getMethod();
        // 获取方法的参数列表,注意此方法需JDK8+
        Parameter[] parameters = method.getParameters();
        // 获取参数列表的实际的值
        Object[] args = joinPoint.getArgs();
        // 建立参数列表和实际的值的对应关系
        Pair<Parameter, Object>[] parameterObjectPairs = new Pair[parameters.length];
        for(int i = 0; i < parameters.length; i++) {
            parameterObjectPairs[i] = new Pair<>(parameters[i], args[i]);
        }
        // 对参数进行遍历
        for(int i = 0; i < parameterObjectPairs.length; i++) {
            Pair<Parameter, Object> pair = parameterObjectPairs[i];
            Parameter parameter = pair.getKey();
            Object arg = pair.getValue();
            // 获取参数的注解列表
            NotNull[] notNulls = parameter.getAnnotationsByType(NotNull.class);
            // 如果发现没有@NotNull注解则校验下一个参数
            if(notNulls.length == 0) {
                continue;
            }
            // 如果发现参数有@NotNull注解并且实际值为null则抛出异常
            if(arg == null) {
                throw new ParameterIsNullException(method, i + 1);
            }
        }
        // 校验通过后继续往下执行实际的方法
        return joinPoint.proceed();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值