guava做本地缓存

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"

欢迎大家关注我的微信公众号,购物优惠券
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值