异步任务问题 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
qm332207252
V2EX    Java

异步任务问题

  •  
  •   qm332207252 Jan 20, 2021 2996 views
    This topic created in 1922 days ago, the information mentioned may be changed or developed.

    一个接口,接收到一次请求,调用 service 执行异步任务,异步任务执行中,直接返回响应,再次请求该接口或者其他用户请求该接口(更或者是自动任务执行),调用 service,上次请求这个任务还在执行中,因此返回处理中,这种 java 后台有比较好的实现吗?

    15 replies    2021-01-21 11:44:00 +08:00
    dqzcwxb
        1
    dqzcwxb  
       Jan 20, 2021
    加个锁
    stonewu
        2
    stonewu  
       Jan 20, 2021
    最简单的方式就是定义一个全局变量
    qm332207252
        3
    qm332207252  
    OP
       Jan 20, 2021
    @dqzcwxb 能详细点说明下不
    zoharSoul
        4
    zoharSoul  
       Jan 20, 2021
    记到任务表.
    qm332207252
        5
    qm332207252  
    OP
       Jan 20, 2021
    @stonewu 我也想过在调用异步方法外面用个什么变量标记执行状态
    MicroGalaxy
        6
    MicroGalaxy  
       Jan 20, 2021
    这种需求还是全局变量最简单好用
    qm332207252
        7
    qm332207252  
    OP
       Jan 20, 2021
    @MicroGalaxy 类似前端做登录按钮,请求表格数据什么的异步请求加状态标记那样咯?
    killergun
        8
    killergun  
       Jan 20, 2021
    Ticket ?根据 Ticket 来获取进展
    guoyuchuan
        9
    guoyuchuan  
       Jan 20, 2021
    异步任务可以配置线程池,这样就不会存在你说的这个问题了
    guoyuchuan
        10
    guoyuchuan  
       Jan 20, 2021
    @guoyuchuan #9 不对,说错了
    liian2019
        11
    liian2019  
       Jan 20, 2021
    单机就整个 AtomicBoolean,分布式就整个 redis 记一下
    RedBeanIce
        12
    RedBeanIce  
       Jan 20, 2021
    java 异步任务有很多方法,CompletableFuture.runAsync

    至于第二次进来的问题,加个锁就行,楼上有说明,单机和分布式
    itechify
        13
    itechify  
    PRO
       Jan 20, 2021 via Android
    单机还是集群,单机配只静态变量,集群搞 redis,加个 key 标识
    siweipancc
        14
    siweipancc  
       Jan 21, 2021 via iPhone
    占坑#
    siweipancc
        15
    siweipancc  
       Jan 21, 2021
    @Log
    @RestController
    @SpringBootApplication
    public class WebApplication {

    public static void main(String[] args) {
    SpringApplication.run(WebApplication.class, args);
    }

    static final String CREATED = "create";
    static final String PROCESS = "process";
    static final String COMPLETE = "complete";


    @PostMapping("generate")
    public ResponseEntity<Response> generate(@RequestBody Request request) {
    return ResponseEntity.ok(generate(request.input, request.taskId));
    }


    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private ThreadPoolTaskExecutor executor;

    @PostConstruct
    public void init() {
    redisTemplate.setKeySerializer(RedisSerializer.string());
    redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }

    Function<UUID, String> valKeyFunc = uuid -> "value::" + uuid;
    Duration expire = Duration.ofMinutes(30L);

    public Response generate(Integer input, UUID taskId) {

    if (taskId == null) {
    check(input != null, "请输入值");
    UUID uuid = createTask(input);
    return new Response(CREATED, null, uuid, expire.getSeconds());
    }

    String key = valKeyFunc.apply(taskId);
    Long expire = redisTemplate.getExpire(key);
    Entity value;
    try {
    value = (Entity) redisTemplate.opsForValue().get(key);
    } catch (ClassCastException e) {
    log.warning(e.getMessage());
    e.printStackTrace();
    throw new RuntimeException("服务器内部错误");
    }
    check(value != null, "任务 " + taskId + " 不存在或者已经过期");
    assert value != null;
    check(value.complete != null, "服务器内部错误");
    if (!value.complete) {
    return new Response(PROCESS, null, taskId, expire);
    }

    return new Response(COMPLETE, value, taskId, expire);
    }


    private static void check(Boolean condition, String msg) {
    if (!Boolean.TRUE.equals(condition)) {
    throw new RuntimeException(msg);
    }
    }


    private UUID createTask(Integer input) {
    UUID uuid = UUID.randomUUID();
    executor.execute(() -> {
    try {
    Entity entity = new Entity(uuid, false, new Date(), null, input, null);
    log.info(String.format("begin task: %s, input: %s", uuid, input));
    String key = valKeyFunc.apply(uuid);
    redisTemplate.opsForValue().set(key, entity, expire);
    log.info(String.format("set task: %s, input: %s, key: %s", uuid, input, key));
    TimeUnit.SECONDS.sleep(RandomUtil.randomInt(10, 20));
    String value = RandomUtil.randomString(Math.abs(input));
    entity.complete = true;
    entity.completeTime = new Date();
    entity.output = value;
    log.info(String.format("end task: %s, input: %s, generated: %s", uuid, input, value));
    redisTemplate.opsForValue().set(key, entity, expire);
    } catch (InterruptedException e) {
    log.warning(e.getMessage());
    e.printStackTrace();
    }
    });
    return uuid;
    }

    @Data
    static class Request {
    Integer input;
    UUID taskId;
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    static class Response {
    String status;
    Object data;
    UUID taskId;
    Long expire;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Entity {
    UUID taskId;
    Boolean complete;
    Date beginTime;
    Date completeTime;

    Integer input;
    String output;
    }

    }
    About     Help     Advertise     Blog     API     FAQ     Solana     3575 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 98ms UTC 04:52 PVG 12:52 LAX 21:52 JFK 00:52
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86