• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

java 异步执行代码(先返回结果,后执行代码

武飞扬头像
天狼1222
帮助2

业务场景:

        在用户那,角色那变更后,要更新数据,因为更新要比较长时间,需要先返回结果(2:已接收待执行)。更新结束后,再返回值结果。

(执行结果. 0:执行失败 ; 1:执行成功; 2:已接收待执行)

处理1: 简单异步

使用 ExecutorService 异步

  1.  
    public void onCallback(JSONObject param) {
  2.  
    ExecutorService executor = Executors.newCachedThreadPool();
  3.  
    executor.execute(() -> {
  4.  
    try {
  5.  
    Thread.sleep(1000 * 10);
  6.  
    } catch (InterruptedException e) {
  7.  
    e.printStackTrace();
  8.  
    }
  9.  
    // 这边执行具体的方法
  10.  
    this.syncDealResult(param);
  11.  
     
  12.  
    });
  13.  
    executor.shutdown();
  14.  
    }
  15.  
     
  16.  
    public JSONObject dealResult(JSONObject params) {
  17.  
    // 先返回结果,然后异步执行
  18.  
    this.onCallback(params);
  19.  
    JSONObject result = new JSONObject();
  20.  
    result.put("excRs", "2");
  21.  
    return result;
  22.  
    }
  23.  
     
  24.  
     
  25.  
    public void syncDealResult(JSONObject params) {
  26.  
    logger.info("deal abRole param {}", JSON.toJSONString(params));
  27.  
    String logId = MapUtils.getString(params, "logId");
  28.  
    String excRs = "1";
  29.  
    try {
  30.  
    // 具体操作
  31.  
    } catch (Exception e) {
  32.  
    e.printStackTrace();
  33.  
    excRs = "-1";
  34.  
    }
  35.  
    logger.info("update abRole finish callRecordId {}, excRs {}", logId, excRs);
  36.  
    // 处理完后推送结果
  37.  
    JSONObject param = new JSONObject();
  38.  
    param.put("logId", logId);
  39.  
    param.put("excRs", excRs);
  40.  
    // 推送结果
  41.  
    }
学新通

加 Thread.sleep(1000 * 10); 就明显看得出差别了。

如果是有多种异步执行,比如:A执行完后,B要做通知;C要入库;D要做统计,这时候要怎么处理呢?

处理2:多个异步执行

IRoleCallback

  1.  
    import com.alibaba.fastjson.JSONObject;
  2.  
    import org.apache.commons.lang3.StringUtils;
  3.  
     
  4.  
    /**
  5.  
    * AB角色异步调用接口
  6.  
    *
  7.  
    */
  8.  
    public interface IRoleCallback {
  9.  
     
  10.  
    /**
  11.  
    * Computes a result, or throws an exception if unable to do so.
  12.  
    *
  13.  
    * @param param 结果
  14.  
    * @return computed result
  15.  
    * @throws Exception if unable to compute a result
  16.  
    */
  17.  
    Object call(JSONObject param) throws Exception;
  18.  
     
  19.  
    /**
  20.  
    * unique name of callback
  21.  
    *
  22.  
    * @return callback name
  23.  
    */
  24.  
    default String name() {
  25.  
    return StringUtils.uncapitalize(getClass().getSimpleName());
  26.  
    }
  27.  
     
  28.  
    /**
  29.  
    * prior to callback 用于排序
  30.  
    *
  31.  
    * @return order
  32.  
    */
  33.  
    default double order() {
  34.  
    return 1.0d;
  35.  
    }
  36.  
     
  37.  
    }
学新通

RoleCallbackRegister

  1.  
    import java.util.*;
  2.  
     
  3.  
    public class RoleCallbackRegister {
  4.  
    private static final Map<String, IRoleCallback> CALLBACKS = new HashMap<>();
  5.  
     
  6.  
    public static boolean register(IRoleCallback callback) {
  7.  
    if (CALLBACKS.containsKey(callback.name())) {
  8.  
    return false;
  9.  
    }
  10.  
    CALLBACKS.put(callback.name(), callback);
  11.  
    return true;
  12.  
    }
  13.  
     
  14.  
    public static List<IRoleCallback> getCallbacks() {
  15.  
    List<IRoleCallback> roleCallbacks = new ArrayList<>(CALLBACKS.values());
  16.  
    roleCallbacks.sort(Comparator.comparingDouble(IRoleCallback::order));
  17.  
    return roleCallbacks;
  18.  
    }
  19.  
    }
学新通

SpringUtils

  1.  
    @Component
  2.  
    public class SpringUtils implements ApplicationContextAware {
  3.  
     
  4.  
    private static ApplicationContext applicationContext;
  5.  
     
  6.  
    @Override
  7.  
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  8.  
    SpringUtils.applicationContext = applicationContext;
  9.  
    }
  10.  
     
  11.  
    public static Object getBean(String name) {
  12.  
    return applicationContext.getBean(name);
  13.  
    }
  14.  
     
  15.  
    public static <T> T getBean(Class<T> clazz) {
  16.  
    return applicationContext.getBean(clazz);
  17.  
    }
  18.  
    }
学新通

AbstractRoleCallbackImpl

  1.  
    import com.web.work.common.support.SpringUtils;
  2.  
    import com.alibaba.fastjson.JSONObject;
  3.  
    import org.apache.commons.lang3.StringUtils;
  4.  
    import org.slf4j.Logger;
  5.  
    import org.slf4j.LoggerFactory;
  6.  
    import org.springframework.beans.factory.InitializingBean;
  7.  
     
  8.  
    public abstract class AbstractRoleCallbackImpl implements IRoleCallback, InitializingBean {
  9.  
    protected final Logger logger = LoggerFactory.getLogger(getClass());
  10.  
     
  11.  
    @Override
  12.  
    public Object call(JSONObject param) throws Exception {
  13.  
    return doCall(param);
  14.  
    }
  15.  
     
  16.  
    protected abstract Object doCall(JSONObject param) throws Exception;
  17.  
     
  18.  
    @Override
  19.  
    public String name() {
  20.  
    return StringUtils.uncapitalize(getClass().getSimpleName());
  21.  
    }
  22.  
     
  23.  
    @Override
  24.  
    public void afterPropertiesSet() {
  25.  
    boolean register = RoleCallbackRegister.register(SpringUtils.getBean(this.getClass()));
  26.  
    if (!register) {
  27.  
    logger.error("register role callback name:{} failed.", name());
  28.  
    } else {
  29.  
    logger.info("register role callback name:{} succeed.", name());
  30.  
    }
  31.  
    }
  32.  
    }
学新通

RoleCallBackService

  1.  
    @Service
  2.  
    public class RoleCallBackService implements InitializingBean, DisposableBean {
  3.  
     
  4.  
    private final static Logger logger = LoggerFactory.getLogger(RoleCallBackService.class);
  5.  
     
  6.  
    private ThreadPoolExecutor pool;
  7.  
     
  8.  
    public void onCallback(JSONObject param) {
  9.  
    pool.execute(() -> {
  10.  
    RoleCallbackRegister.getCallbacks().forEach(x -> {
  11.  
    try {
  12.  
    logger.info("call {}", x.name());
  13.  
    x.call(param);
  14.  
    } catch (Exception e) {
  15.  
    logger.error("回调{}接口失败:", x.name(), e);
  16.  
    }
  17.  
    });
  18.  
    });
  19.  
    }
  20.  
     
  21.  
    @Override
  22.  
    public void afterPropertiesSet() {
  23.  
    int size = Runtime.getRuntime().availableProcessors() 1;
  24.  
    pool = new ThreadPoolExecutor(size, size * 2, 300L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000),
  25.  
    Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
  26.  
    }
  27.  
     
  28.  
    @Override
  29.  
    public void destroy() throws Exception {
  30.  
    pool.shutdown();
  31.  
    }
  32.  
    }
学新通

RoleUpdateService

  1.  
    @Service
  2.  
    public class RoleUpdateService extends AbstractRoleCallbackImpl {
  3.  
     
  4.  
    private final static Logger logger = LoggerFactory.getLogger(RoleUpdateService.class);
  5.  
     
  6.  
    @Override
  7.  
    protected Object doCall(JSONObject params) throws Exception {
  8.  
    Thread.sleep(1000 * 10);
  9.  
    logger.info("deal abRole param {}", JSON.toJSONString(params));
  10.  
    String logId = MapUtils.getString(params, "logId");
  11.  
    String excRs = "1";
  12.  
    try {
  13.  
    // 执行更新操作
  14.  
    } catch (Exception e) {
  15.  
    e.printStackTrace();
  16.  
    excRs = "-1";
  17.  
    }
  18.  
    logger.info("update abRole finish callRecordId {}, excRs {}", logId, excRs);
  19.  
    // 处理完后推送结果
  20.  
    JSONObject param = new JSONObject();
  21.  
    param.put("logId", logId);
  22.  
    param.put("excRs", excRs);
  23.  
    logger.info("update role record {}", JSON.toJSONString(param));
  24.  
    // 推送结果
  25.  
    return "";
  26.  
    }
  27.  
    }
学新通

先返回结果后执行

  1.  
    @Resource
  2.  
    private RoleCallBackService roleCallBackService;
  3.  
     
  4.  
    public JSONObject dealResult(JSONObject params) {
  5.  
    // 先返回结果,然后异步执行
  6.  
    try {
  7.  
    roleCallBackService.onCallback(params);
  8.  
    } catch (Exception e) {
  9.  
    e.printStackTrace();
  10.  
    }
  11.  
    JSONObject result = new JSONObject();
  12.  
    result.put("excRs", "2");
  13.  
    return result;
  14.  
    }

总结:

        要先返回结果,后执行内容,需要使用异步的方式,用ExecutorService进行处理。如果是单个的,就直接调用比较简单。如果是多个的,就先要注册下,然后遍历去调用。 

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanheckihk
系列文章
更多 icon
同类精品
更多 icon
继续加载