jfinal 注解@interface,接口访问次数限制

发布时间:2018-04-30作者:laosun阅读(3679)

jfinal

jfinal使用注解@interface方式,实现接口的访问次数限制

    在开发中,难免会遇到接口的访问次数限制等功能,比如防止狂刷,验证码的请求次数限制等。

    下边博主使用jfinal + redis实现了这一个功能。

    首先创建@interface类

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Inherited
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.METHOD})
    public @interface RequestLimit {
        /**
         * 
         * 允许访问的次数,默认值MAX_VALUE
         */
        long count() default Integer.MAX_VALUE;
    
        /**
         * 
         * 时间段,单位为秒,默认值一分钟
         */
        int time() default 60;
    }


    然后创建拦截器.

    import com.jfinal.aop.Interceptor;
    import com.jfinal.aop.Invocation;
    import com.jfinal.kit.PropKit;
    import com.jfinal.plugin.redis.Cache;
    import com.jfinal.plugin.redis.Redis;
    import com.sunjs.utils.IpUtils;
    
    /**
     * LimitInterceptor.
     */
    public class LimitInterceptor implements Interceptor {
    	
    	public void intercept(Invocation inv) {
    		RequestLimit limit = inv.getMethod().getAnnotation(RequestLimit.class);
    		if (limit != null){
    			long count = limit.count();
    			int time = limit.time();
    			
    			String ip = IpUtils.getIpAddr(inv.getController().getRequest());
    			
    			String uri = inv.getController().getRequest().getRequestURI();
    			
    			/** 操作redis cache **/
    			String cacheKey = "visit_limit_"+uri+"_"+ip;
    			Cache cache = Redis.use(PropKit.get("redis.cachename"));
    			Long visitNum = cache.incr(cacheKey);
    			if(visitNum==1){
    				//第一次访问需要在redis中增加过期时间
    				cache.expire(cacheKey, time);
    			}
    			if (visitNum > count) {  
    				inv.getController().renderJson("请求次数频繁,请稍后重试");
    				return ;
    	        }  
    		}
    		inv.invoke();
    	}
    	
    }

    获取ip的工具类这里就不公布了,网上一搜一大堆。

    具体如何限制访问次数,自己去扩展吧,比如返回页面,返回json,或者输入验证码才可以进行下一步....

    记得在config启动加载中配置此拦截器

    public void configInterceptor(Interceptors me) {
    		me.add(new LimitInterceptor());
    	}

    配置redis插件

    public void configPlugin(Plugins me) {
    		
    		// 用于缓存博客模块的redis服务
    		RedisPlugin newsRedis = new RedisPlugin(PropKit.get("redis.cachename"),
    				PropKit.get("redis.host"), PropKit.getInt("redis.port"),
    				PropKit.getInt("redis.timeout"), PropKit.get("redis.password"));
    	    me.add(newsRedis);
    	}

    然后在请求方法中就可以注解了,很简单的小例子。

    @RequestLimit(count=60, time=60)  //60秒请求次数限制60次


3 +1

版权声明

 Java  源码

 请文明留言

1 条评论