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();
}
}