借助 redis,
根據(jù)業(yè)務(wù)設(shè)計(jì)唯一的 key.
使用配置參數(shù)(一定時(shí)間內(nèi)可發(fā)送的次數(shù))count作為 value
使用配置參數(shù)(時(shí)間)作為該 key的過期時(shí)間.
邏輯:
每次發(fā)送時(shí)檢查是否存在該 key,和次數(shù)是否達(dá)到上限,已達(dá)上限不發(fā)送;
如果不存在或者未達(dá)上限,則發(fā)送,然后 count++,同時(shí)更新過期時(shí)間
ps:
關(guān)于過期時(shí)間有兩點(diǎn)歧義:是否需要續(xù)期,因此做成了可配置的.
public class LimitService {
private final String value = "value";
private final String createTime = "create_time";
Jedis jedis;
@Before
public void before() {
jedis = new Jedis("localhost");
}
@Test
public void test() {
execute();
}
private static final int count=2;
private static final int second=10;
//數(shù)值變化更新有效期
private static final boolean INCREASE_VALUE_REFRESH_TTL = false;
private static final String key = "limit_component";
public void execute() {
if (check()) {
System.out.println("執(zhí)行方法");
}
}
private boolean check() {
boolean result ;
int currentCount=0;
if (!jedis.exists(key)) {
result = true;
setKey(currentCount);
} else {
String s = jedis.hget(key, value);
currentCount= Convert.toInt(s);
if (currentCount >= count) {
//大于等于超限啦
result = false;
} else {
result = true;
setKey(currentCount);
}
}
System.out.println(StrUtil.format("檢查結(jié)果【{}】",result));
return result;
}
private void setKey(int currentCount) {
currentCount++;
Boolean exists = jedis.exists(key);
jedis.hset(key, value, Convert.toStr(currentCount));
if (INCREASE_VALUE_REFRESH_TTL ||!exists) {
//續(xù)期
jedis.expire(key, second);
if (!exists) {
jedis.hset(key, createTime, Convert.toStr(System.currentTimeMillis()));
}
}
}
}
后邊會(huì)考慮使用注解來定義配置項(xiàng)