Guava:常用功能,防止阁下重复造轮子

34 篇文章 0 订阅
11 篇文章 0 订阅

1. 本地缓存

    /**
     * 功能:缓存
     * 文档:<a href="https://github.com/google/guava/wiki/CachesExplained">CachesExplained</a>
     */
    @Test
    public void test_cache() {
        Cache<String, String> cache = CacheBuilder.newBuilder()
                // 最大存储条数,缓存将尝试逐出最近或不经常使用的条目
                .maximumSize(10000)
                // 可以设定删除时候的权重判断
                //.weigher((Weigher<String, String>) (x, y) -> x.length() - y.length())
                // 有效时间
                .expireAfterWrite(3, TimeUnit.SECONDS)
                // 记录次数
                .recordStats()
                .build();

        cache.put("Lasse", "You are handsome.");
        log.info("测试结果:{}", cache.getIfPresent("Lasse"));

        cache.invalidate("Lasse"); // cache.invalidateAll(); 也可以全部删除
        log.info("测试结果:{}", cache.getIfPresent("Lasse"));

        log.info("测试结果:{}", cache.stats());
    }

2. MQ

    @Test
    public void test_eventbus() {
        EventBus eventBus = new EventBus();
        eventBus.register(new Listener());
        // 可以由其他服务推送消息,之后就可以在监听中收到了
        eventBus.post("消息总线,订单号:100001");
    }

    static class Listener {
        @Subscribe
        public void handleEvent(String orderId) {
            log.info("测试结果:{}", orderId);
        }
    }

3. 并发回调

    /**
     * 功能:并发回调
     * 文档:https://github.com/google/guava/wiki/ListenableFutureExplained
     */
    @Test
    public void test_ListenableFuture() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);

        ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
        ListenableFuture<String> explosion = executorService.submit(() -> "finished");

        ExecutorService callBackService = Executors.newFixedThreadPool(1);
        Futures.addCallback(explosion, new FutureCallback<String>() {
            public void onSuccess(String explosion) {
                System.out.println("onSuccess");
                countDownLatch.countDown();
            }

            public void onFailure(Throwable thrown) {
                System.out.println("onFailure");
                countDownLatch.countDown();
            }
        }, callBackService);

        countDownLatch.await();
    }

4. 布隆过滤器

    /**
     * 功能:布隆过滤器
     * 文档:https://github.com/google/guava/wiki/HashingExplained#bloomfilter
     */
    @Test
    public void test_BloomFilter() {
        BloomFilter<String> bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()),
                1000,
                0.01);

        // 向布隆过滤器中添加元素
        bloomFilter.put("apple");
        bloomFilter.put("banana");
        bloomFilter.put("orange");

        // 检查元素是否存在于布隆过滤器中
        System.out.println(bloomFilter.mightContain("apple"));   // true
        System.out.println(bloomFilter.mightContain("banana"));  // true
        System.out.println(bloomFilter.mightContain("orange"));  // true
        System.out.println(bloomFilter.mightContain("grape"));   // false

        // 输出布隆过滤器的统计信息
        System.out.println("Expected FPP: " + bloomFilter.expectedFpp());
        System.out.println("Number of Inserted Elements: " + bloomFilter.approximateElementCount());
    }

5. 反射工具包

    /**
     * 功能:反射
     * 文档:https://github.com/google/guava/wiki/ReflectionExplained
     */
    @Test
    public void test_Invokable() throws NoSuchMethodException {
        Method method = UserEntity.class.getMethod("getCreateTime");
        Invokable<?, ?> invokable = Invokable.from(method);
        log.info("测试结果 - 方法名称:{}", invokable.getName());
        log.info("测试结果 - 参数类型:{}", JSON.toJSONString(invokable.getTypeParameters()));
        log.info("测试结果 - 静态判断:{}", invokable.isStatic());
        // !(Modifier.isFinal(method.getModifiers()) || Modifiers.isPrivate(method.getModifiers()) || Modifiers.isStatic(method.getModifiers()) || Modifiers.isFinal(method.getDeclaringClass().getModifiers()))
        log.info("测试结果 - isOverridable:{}", invokable.isOverridable());
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值