V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
choice4
V2EX  ›  Java

异步日志打印

  •  
  •   choice4 · 2018-12-20 11:25:48 +08:00 · 2426 次点击
    这是一个创建于 1926 天前的主题,其中的信息可能已经有所发展或是发生改变。

    日志打印使用 Future 和主线程是什么关系的 如果 future = executorService.submit(new Callable()); s = future.get(); log.info(s); 这绝对是没事的。 如果写在内部调用 log.info(executorService.submit(new Callable()).get());
    或者 log.info(executorService.submit(new Callable()).get() == null ? "null" : "not null"); 这也是不行的 打印不出来 那么如果直接 log 输出方法内部调用异步方法的话 log.info()方法看到的是什么? 是无参的 Log.info()吗?

    因为如果断点卡住主线程的话,卡一下就能打印出来。

    logback。

    7 条回复    2018-12-20 13:56:06 +08:00
    choice4
        1
    choice4  
    OP
       2018-12-20 11:32:33 +08:00
    题目描述错了(试了一下没出现我说的那种情况),说实际情况吧。
    昨天看到有个老哥发的 jedis bug 然后下面说出了 lettuce
    今天就说试一下 lettuce
    创建的 RedisAsyncCommands
    然后 log.info( asyncCommands.get("key").get() ); 这种打印不出来。 可能是 lettuce 这个异步命令的事吧
    0915240
        2
    0915240  
       2018-12-20 13:23:10 +08:00
    lovedebug
        3
    lovedebug  
       2018-12-20 13:24:27 +08:00
    异步调用没返回你怎么打印结果
    choice4
        4
    choice4  
    OP
       2018-12-20 13:29:37 +08:00
    @lovedebug 你有没有写代码试一下
    choice4
        5
    choice4  
    OP
       2018-12-20 13:43:56 +08:00
    平常 jdk 的调用方式
    ExecutorService service = Executors.newFixedThreadPool(1);
    log.error(service.submit(() -> {
    Thread.sleep(30000);
    return 100;
    }).get().toString());
    service.shutdown();
    这样可以在 get()方法处阻塞获取值 ,最后成功打印。
    但是

    RedisClient redisClient = RedisClient.create("redis://127.0.0.1:6379");
    StatefulRedisConnection<String, String> redisConnection = redisClient.connect();
    RedisAsyncCommands<String, String> asyncCommands = redisConnection.async();
    RedisFuture<String> future = asyncCommands.get("lettuce_key");
    future.whenCompleteAsync((s, throwable) -> {
    try {
    log.error(asyncCommands.get("lettuce_key").get());
    } catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
    }
    });

    这样是空的,
    如果在 future.whenCompleteAsync 处断点卡上一下的话。就可以打印了
    choice4
        6
    choice4  
    OP
       2018-12-20 13:50:53 +08:00
    是因为主线程结束太快了
    lihongjie0209
        7
    lihongjie0209  
       2018-12-20 13:56:06 +08:00
    你的 future 结束了吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5413 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:00 · PVG 17:00 · LAX 02:00 · JFK 05:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.