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

1. 本地缓存

    /**
     * 功能:缓存
     * 文档:CachesExplained
     */
    @Test
    public void test_cache() {
        Cache cache = CacheBuilder.newBuilder()
                // 最大存储条数,缓存将尝试逐出最近或不经常使用的条目
                .maximumSize(10000)
                // 可以设定删除时候的权重判断
                //.weigher((Weigher) (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 explosion = executorService.submit(() -> "finished");

        ExecutorService callBackService = Executors.newFixedThreadPool(1);
        Futures.addCallback(explosion, new FutureCallback() {
            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 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());
    }

你可能感兴趣的:(常用,学习日记,Guava,java,guava)