`
tuhaitao
  • 浏览: 375379 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

接口调用频率限制代码

    博客分类:
  • java
阅读更多

有很多时候我们写的代码不是你想跑多快就能跑多快的, 因为一些陈旧的核心系统支撑不了,在此万般无奈的情况下,

 

调用老系统的接口,服务 就需要运维给一个可以接受的范围参考, 情景大概是这样,现实还是很难接受,明明写好的代码

 

还用了一些自己优化技术来使代码运行的更快, 现实都是残酷的,不那么完美的, 与其被弓虽女干,不如好好享受一番。

 

 

分享一下基于ThreadLocal限制调用频率的代码:

 

其中引入了commons-lang里的StopWatch计时器

 

 

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.opencfg.core.limit;

import org.apache.commons.lang.time.StopWatch;

/**
 * <p>
 * Frequence Utils
 * <p>
 * 
 * <p>#ThreadSafe#</p>
 * 
 * @author Opencfg Software Foundation
 * @since 0.0.1-SNAPSHOT
 * @version $Id: FrequenceUtils.java 2011-06-11 23:58:53 reymondtu $
 */
public final class FrequenceUtils {

	/**
	 * <p>
	 * Limit call count in split time
	 * </p>
	 * 
	 * @param limitSplitTime
	 * @param limitCount
	 * @throws InterruptedException
	 */
	public static void limit(final long limitSplitTime, final int limitCount) throws InterruptedException {
		FrequenceUnit funit = threadLocal.get();
		funit.limitSplitTime = limitSplitTime;
		funit.limitCount = limitCount;
		funit.watch.split();
		long diffTime = funit.limitSplitTime - funit.watch.getSplitTime();
		if (diffTime >= 0) {
			if (funit.realCount >= funit.limitCount) {
				funit.watch.suspend();
				Thread.sleep(diffTime);
				funit.watch.resume();
				funit.realCount = 0;
			}
		}
		funit.realCount++;
	}
	
	/**
	 * FrequenceUnit
	 */
	private static class FrequenceUnit {		
		FrequenceUnit() {
			this.watch = new StopWatch();
		}
		long limitSplitTime;
		int limitCount;
		StopWatch watch;		
		int realCount = 0;
	}

	private static ThreadLocal<FrequenceUnit> threadLocal = new ThreadLocal<FrequenceUnit>(){
        protected synchronized FrequenceUnit initialValue() {
        	FrequenceUnit funit = new FrequenceUnit();
        	funit.watch.start();
            return funit;
        }
    };

}

 

 

下边是测试用例:

 

 

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.opencfg.core.limit;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * <p>
 * Frequence Utils Test
 * <p>
 * 
 * <p>JUnit4 Test</p>
 * 
 * @author Opencfg Software Foundation
 * @since 0.0.1-SNAPSHOT
 * @version $Id: FrequenceUtilsTest.java 2011-06-12 01:36:53 reymondtu $
 */
public class FrequenceUtilsTest {

	@Test
	public void testLimit() throws InterruptedException {
		FrequenceTestClass ftc = new FrequenceTestClass(1000, 10);
		for(int i = 0; i < 100; i++) {
			ftc.method(i);
		}
		assertTrue(true);
	}
	
	@Test
	public void testLimitMutiThreads() throws InterruptedException {
		Thread t1 = new Thread(new FrequenceTestClass(1000, 10));
		t1.start();
		
		Thread t2 = new Thread(new FrequenceTestClass(1000, 20));
		t2.start();

		Thread.sleep(10000);
	}

	class FrequenceTestClass implements Runnable {
		final long limitTime;
		final int limitCount;
		FrequenceTestClass(final long limitTime, final int limitCount) {
			this.limitTime = limitTime;
			this.limitCount = limitCount;
		}
		public void method(int i) throws InterruptedException {
			FrequenceUtils.limit(limitTime, limitCount);
			System.out.println("tid:" + Thread.currentThread().getId() + ", i=" + i);
		}

		@Override
		public void run() {
			for(int i = 0; i < 100; i++) {
				try {
					method(i);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
分享到:
评论

相关推荐

    API 调用次数限制实现

    我们在开发接口服务器的过程中,为了防止客户端对于接口的滥用,保护服务器的资源, 通常来说我们会对于服务器上的各种接口进行调用次数的限制。

    微信公众号开发文档

    1.服务号与订阅号区别简介 2.各接口功能简介与使用 3.各接口调用频率限制 4.全局返回码说明

    python装饰器-限制函数调用次数的方法(10s调用一次)

    这是博主最近一家大公司的面试题,写一个装饰器,限制函数每10s调用一次。当时是笔试的,只写了大概的代码,回来后温习了python装饰器的基础知识,把代码写完了。决定写篇博客记录下。 装饰器分为带参数得装饰器以及...

    基于AT89S52 单片的频率计

    频率计的基本原理是用一个频率稳定度高的频率源作为基准时钟,对比测 量其他信号的频率。通常情况下计算每秒内待测信号的脉冲个数,此时我们称 闸门时间为1 秒。闸门时间也可以大于或小于一秒。闸门时间越长,得到的...

    js中的节流和防抖的区别及应用场景

    函数节流(throttle)和防抖(debounce):是一种性能优化手段 一、函数节流 类比生活中的例子。...使用节流函数限制接口调用频率,优化性能。 节流函数 //节流函数,只有大于设定的周期才会执行第二次 fu

    java实现微信小程序-音视频、图片内容安全识别

    应用场景 语音风险识别:用户发表的语音内容检测 图片智能鉴黄:对拍照图片的内容鉴黄信息检测 敏感人脸识别:用户的头像、文章图片...单个appid被限制调用频率如下:2000次/分钟,200000次/天 单个文件大小不能超过10M

    详解Java分布式IP限流和防止恶意IP攻击方案

    主要介绍了详解Java分布式IP限流和防止恶意IP攻击方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    淘客帝国_TaodiV_5.40.002完美破解版

    App Key轮换功能:当一个App Key超频则自动切换到下一个App Key有效解决因API调用频率不够而无法调取到商品数据的情况! 其他高级功能:更多功能不再细致描述! 【V5.40.001更新内容】 整合淘宝JSSDK,采用新API...

    函数节流和函数防抖(键盘输入完成触发搜索).rar

    节流保证一段时间内只执行一次核心代码,防抖其实就是搜索功能的实现。。。。滚动浏览器滚动条的时候,更新页面上的...同样的,如果不对函数调用的频率加以限制的话,那么可能我们滚动一次滚动条就会产生N次的调用了。

    自己封装的上海移动EMPP协议,OCX

    10004:超过允许发给该用户的最大发信频率(对此类型错误,客户端可延时一段时间后重试短信发送) 10005:服务忙,请稍后再发短信(对此类型错误,客户端可延时一段时间后重试短信发送) 10006:向网关发送短信失败...

    淘客帝国v5.23官方稳定版无限制破解版

    App Key轮换功能:当一个App Key超频则自动切换到下一个App Key有效解决因API调用频率不够而无法调取到商品数据的情况! 其他高级功能:更多功能不再细致描述! 【V5.23更新内容】 处理淘宝新的修改问题,去除站内...

    微信公众平台应用开发:方法、技巧与案例.(机械工业.柳峰)

     5.5 接口调用频率限制 112  5.6 案例:网址导航 112  5.6.1 案例功能描述 113  5.6.2 案例开发准备 113  5.6.3 封装通用工具类 115  5.6.4 封装菜单工具类 118  5.6.5 创建自定义菜单 120  5.6.6 ...

    站长俱乐部新闻发布系统 V5.21

     3、系统是否和其它论坛集成,很多公司需要论坛和客户交流,所以需要有集成论坛的接口;  4、系统的栏目顺序能否调整,公司业务发生变化,栏目顺序肯定要能随之变化。  第三:易用。试用新闻发布系统时一定要注意...

    window32 API大全 win32编程

    Win32 API作为 Microsoft 32位平台(包括:Windows 9x,Windows NT3.1/4.0/5.0,WindowsCE)的应用程序编程接口,它是构筑所有32位Windows平台的基石,所有在Windows平台上运行的应用程序都可以调用这些函数。...

    MSP430手册

    2.2 代码存储器 2.3 数据存储器(RAM) 2.4 运行控制 2.5 外围模块 2.6 振荡器、倍频器和时钟发生器 3 系统复位、中断和运行模式 3.1 系统复位和初始化 3.2 中断系统结构 3.3 中断处理 3.3.1 SFR中的中断控制位 ...

    计费和客户管理软件boxbilling.zip

    直观的Web 2.0 AJAX供电接口,与100%的可用性得分!客户区可以翻译任何语言。自动化产品创造的托管帐户,域,许可证和下载的产品可以自动完成,成功后收到货款,甚至没有收到付款。也可以创建产品管理员审批后执行...

    c语言编写单片机技巧

    相关频率特性(AC)测试,也是通过外灌一定频率,从I/O口来看输出是否与之匹配。 &#61548; 为了保证IC生产的长期且稳定品质,还会做产品的可靠性测试,这些测试包括ESD测试,LATCH UP测试,温度循环测试,...

    华为编程开发规范与案例

    二、接口类代码问题 第43页 1、对函数参数进行有效性检查 第43页 【案例2.1.1】 第43页 【案例2.1.2】 第43页 【案例2.1.3】 第44页 【案例2.1.4】 第46页 【案例2.1.5】 第47页 【案例2.1.6】 第48页 2、注意多出口...

    网趣网上购物系统的部分特点与精华

    随着网络安全的日益提高,为防止部分恶意人员对商城进行点击或其他不法行为,网趣网上购物系统新增IP访问限制功能,添加某IP后即可限制此IP人员的访问,同时系统支持IP段的限制访问功能,可对同一IP段进行访问限制...

    网趣网上购物系统时尚版V13.0

    新增商品排序功能,由于商品是按添加日期进行排序的,对于添加较早的商品很难再调到前面显示,商品排序可以让任意的商品自由排序,可以方便的调用很早以前添加的商品置于首页或位于某些商品的前面显示。 三四、...

Global site tag (gtag.js) - Google Analytics