package tool;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class GuavaTest {
private static Integer generateNewMsgCode(String phone) {
Integer msgCode = (new Random()).nextInt(1000000 - 100000) + 100000;
System.out.println("generate new Msg code. phone=" + phone + ",msgCode=" + msgCode);
return msgCode;
}
private static LoadingCache<String, Optional<Integer>> msgCodeCache =
CacheBuilder.newBuilder()
.maximumSize(1000L)
.expireAfterWrite(5, TimeUnit.SECONDS)//5s過期
.concurrencyLevel(10)
.build(new CacheLoader<String, Optional<Integer>>() {
@Override
public Optional<Integer> load(String phone) throws Exception {
return Optional.ofNullable(generateNewMsgCode(phone));
}
});
private static Integer getMsgCodeByPhone(String phone){
return msgCodeCache.getUnchecked(phone).orElse(0);
}
public static void main(String[] args) throws InterruptedException {
String phone = "13100000000";
//first
System.out.println("first .msgCode:" + getMsgCodeByPhone(phone));
Thread.sleep(1000);
//second
System.out.println("second .msgCode:" + getMsgCodeByPhone(phone));
Thread.sleep(5000);
//third
System.out.println("third .msgCode:" + getMsgCodeByPhone(phone));
}
}
"com.google.guava:guava:$guavaVersion"
歡迎大家關注我的微信公衆号,購物優惠券
