Search in sources :

Example 11 with UnitRequest

use of info.xiancloud.core.message.UnitRequest in project xian by happyyangyuan.

the class BroadcastSender method asyncSend.

@Override
protected void asyncSend() throws UnitOfflineException, UnitUndefinedException {
    List<UnitInstance> list = UnitRouter.singleton.allInstances(Unit.fullName(unitRequest.getContext().getGroup(), unitRequest.getContext().getUnit()));
    UnitMeta.Broadcast broadcast = list.get(0).getPayload().getMeta().getBroadcast();
    final CountDownLatch latch = new CountDownLatch(list.size());
    Collection<Object> piledUpOutput = new ConcurrentLinkedQueue<>();
    final NotifyHandler tmpHandler = new NotifyHandler() {

        protected void handle(UnitResponse output) {
            if (!broadcast.isSuccessDataOnly()) {
                piledUpOutput.add(output);
            } else if (output.succeeded()) {
                piledUpOutput.add(output.getData());
            }
            latch.countDown();
        }
    };
    for (UnitInstance unitInstance : list) {
        if (unitInstance.getNodeId().equals(LocalNodeManager.LOCAL_NODE_ID)) {
            // we must not share the same unitRequest object while sending request concurrently.
            UnitRequest clonedUnitRequest = CloneUtil.cloneBean(unitRequest, UnitRequest.class);
            /*clonedUnitRequest.getContext().setDestinationNodeId(unitInstance.getNodeId()); no need  */
            new RoutedLocalAsyncSender(clonedUnitRequest, tmpHandler).send();
        } else {
            LOG.debug("In order not to share the same unit request object,we clone a new request");
            UnitRequest clonedRequest = CloneUtil.cloneBean(unitRequest, UnitRequest.class);
            clonedRequest.getContext().setDestinationNodeId(unitInstance.getNodeId());
            LocalNodeManager.send(clonedRequest, tmpHandler);
        }
    }
    if (broadcast.isAsync()) {
        callback.callback(UnitResponse.success());
    } else {
        try {
            if (!latch.await(broadcast.getTimeoutInMilli(), TimeUnit.MILLISECONDS)) {
                LOG.error(new TimeoutException());
                callback.callback(UnitResponse.error(Group.CODE_TIME_OUT, piledUpOutput, "Time out while waiting for all the units to response, the data is only part of the result. "));
            } else {
                callback.callback(UnitResponse.success(piledUpOutput));
            }
        } catch (InterruptedException e) {
            callback.callback(UnitResponse.exception(e));
        }
    }
}
Also used : RoutedLocalAsyncSender(info.xiancloud.core.message.sender.local.RoutedLocalAsyncSender) NotifyHandler(info.xiancloud.core.NotifyHandler) UnitInstance(info.xiancloud.core.distribution.service_discovery.UnitInstance) UnitMeta(info.xiancloud.core.UnitMeta) CountDownLatch(java.util.concurrent.CountDownLatch) UnitRequest(info.xiancloud.core.message.UnitRequest) UnitResponse(info.xiancloud.core.message.UnitResponse) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) TimeoutException(java.util.concurrent.TimeoutException)

Example 12 with UnitRequest

use of info.xiancloud.core.message.UnitRequest in project xian by happyyangyuan.

the class ReceiveAndBroadcast method execute.

@Override
public UnitResponse execute(UnitRequest msg) {
    if (msg.getContext().isRouted()) {
        return execute0(msg);
    } else {
        List<UnitInstance> list = new ArrayList<>();
        String application = msg.get("application", String.class);
        List<UnitInstance> unitInstances;
        try {
            unitInstances = UnitRouter.singleton.allInstances(Unit.fullName(getGroupName(), getUnitName()));
        } catch (UnitOfflineException | UnitUndefinedException e) {
            throw new RuntimeException(e);
        }
        if (StringUtil.isEmpty(application) || ALL.equals(application)) {
            list.addAll(unitInstances);
        } else {
            for (UnitInstance clientInfo : unitInstances) {
                if (clientInfo.getName().equals(msg.getString("application"))) {
                    list.add(clientInfo);
                }
            }
        }
        CountDownLatch latch = new CountDownLatch(list.size());
        List<Object> piledUpOutput = new ArrayList<>();
        for (UnitInstance clientInfo : list) {
            LocalNodeManager.send(new UnitRequest().setContext(RequestContext.create().setGroup(getGroupName()).setUnit(getUnitName()).setDestinationNodeId(clientInfo.getNodeId())), new NotifyHandler() {

                protected void handle(UnitResponse unitResponse) {
                    LOG.info("对" + clientInfo.getNodeId() + "执行" + getName() + "操作完毕");
                    if (!successDataOnly()) {
                        piledUpOutput.add(unitResponse);
                    } else if (unitResponse.succeeded()) {
                        piledUpOutput.add(unitResponse.getData());
                    }
                    latch.countDown();
                }
            });
        }
        if (async()) {
            return UnitResponse.success();
        } else {
            try {
                latch.await(timeoutInMilli(), TimeUnit.MILLISECONDS);
                return UnitResponse.success(piledUpOutput);
            } catch (InterruptedException e) {
                return UnitResponse.exception(e);
            }
        }
    }
}
Also used : UnitOfflineException(info.xiancloud.core.distribution.exception.UnitOfflineException) ArrayList(java.util.ArrayList) NotifyHandler(info.xiancloud.core.NotifyHandler) UnitInstance(info.xiancloud.core.distribution.service_discovery.UnitInstance) CountDownLatch(java.util.concurrent.CountDownLatch) UnitUndefinedException(info.xiancloud.core.distribution.exception.UnitUndefinedException) UnitRequest(info.xiancloud.core.message.UnitRequest) UnitResponse(info.xiancloud.core.message.UnitResponse)

Example 13 with UnitRequest

use of info.xiancloud.core.message.UnitRequest in project xian by happyyangyuan.

the class SendEmail method main.

public static void main(String... args) {
    SendEmail.records.put("happyyangyuan@163.com", new ArrayList<Long>() {

        {
        // add(System.currentTimeMillis());
        // add(System.currentTimeMillis());
        // add(System.currentTimeMillis());
        // add(System.currentTimeMillis());
        }
    });
    new SendEmail().execute(new UnitRequest(new JSONObject() {

        {
            put("subject", "XXX账户密码重置");
            put("recipients", new ArrayList<String>() {

                {
                    add("happyyangyuan@163.com");
                }
            });
            put("content", "您在XXX使用了密码重置功能,请点击下面链接重置密码:\n" + "http://localhost:8080/XXX/ResetPassword?id=jfdsajkfs89878788111");
            put("limit", 3);
            put("scope", 1000 * 30);
        }
    }));
}
Also used : UnitRequest(info.xiancloud.core.message.UnitRequest) JSONObject(com.alibaba.fastjson.JSONObject)

Example 14 with UnitRequest

use of info.xiancloud.core.message.UnitRequest in project xian by happyyangyuan.

the class IUnitAop method intercept.

/**
 * intercept
 */
default void intercept() {
    Collection<Unit> units = getUnitCollection();
    if (units == null || units.isEmpty()) {
        LOG.info("nothing to intercept at all.");
        return;
    }
    final IUnitAop thiz = this;
    for (final Unit originUnit : units) {
        LOG.debug(originUnit.getName() + "    代理对象:" + Proxy.isProxyClass(originUnit.getClass()));
        final Unit nakedUnit;
        if (Proxy.isProxyClass(originUnit.getClass())) {
            nakedUnit = (Unit) ProxyBuilder.getProxyBuilder(originUnit.hashCode()).getMostOriginalObject();
        } else {
            nakedUnit = originUnit;
        }
        Unit proxy = new ProxyBuilder<Unit>(originUnit, true) {

            @Override
            public Object before(Method method, Object[] args) throws UnitResponseReplacement {
                if ("execute".equals(method.getName())) {
                    if (!asyncBefore()) {
                        return thiz.before(nakedUnit, (UnitRequest) args[0]);
                    } else {
                        Runnable runnableForBefore = () -> {
                            try {
                                Object beforeReturnIgnored = thiz.before(nakedUnit, (UnitRequest) args[0]);
                                LOG.info("异步AOP的前置拦截方法before返回的内容被忽略:" + beforeReturnIgnored);
                            } catch (UnitResponseReplacement outputReplacement) {
                                throw new RuntimeException("异步aop不允许打断被拦截的方法!", outputReplacement);
                            }
                        };
                        if (trackMsgIdIfAsync()) {
                            ThreadPoolManager.execute(runnableForBefore, MsgIdHolder.get());
                        } else {
                            ThreadPoolManager.executeWithoutTrackingMsgId(runnableForBefore);
                        }
                        return "";
                    }
                }
                return "";
            }

            @Override
            public void after(Method method, Object[] args, Object unitReturn, Object beforeReturn) throws UnitResponseReplacement {
                if ("execute".equals(method.getName())) /*&& !beforeReturn.toString().equals(AOP_FILTER_PLAG)*/
                {
                    final UnitResponse finalMethodReturn;
                    if (unitReturn instanceof Throwable) {
                        // 有异常抛出,则需要回滚
                        finalMethodReturn = UnitResponse.exception((Throwable) unitReturn);
                    } else {
                        finalMethodReturn = (UnitResponse) unitReturn;
                    }
                    if (!asyncAfter()) {
                        // 同步
                        thiz.after(originUnit, (UnitRequest) args[0], finalMethodReturn, beforeReturn);
                    } else {
                        Runnable runnableAfter = () -> {
                            try {
                                thiz.after(originUnit, (UnitRequest) args[0], finalMethodReturn, beforeReturn);
                            } catch (UnitResponseReplacement outputReplacement) {
                                throw new RuntimeException("异步aop不允许执行此操作!", outputReplacement);
                            }
                        };
                        if (trackMsgIdIfAsync()) {
                            ThreadPoolManager.execute(runnableAfter, MsgIdHolder.get());
                        } else {
                            ThreadPoolManager.executeWithoutTrackingMsgId(runnableAfter);
                        }
                    }
                }
            }
        }.getProxy();
        LocalUnitsManager.replaceUnit(proxy);
    }
}
Also used : Method(java.lang.reflect.Method) Unit(info.xiancloud.core.Unit) UnitRequest(info.xiancloud.core.message.UnitRequest) UnitResponse(info.xiancloud.core.message.UnitResponse) JSONObject(com.alibaba.fastjson.JSONObject)

Example 15 with UnitRequest

use of info.xiancloud.core.message.UnitRequest in project xian by happyyangyuan.

the class DaoUnit method test.

/**
 * 执行sql
 * 仅供内部测试使用
 */
public static void test(Class unitClass, Map<String, Object> map) {
    try {
        DaoUnit daoUnit = (DaoUnit) unitClass.newInstance();
        UnitRequest msg = new UnitRequest(map);
        System.out.println("输出>>>>>>>>  " + JSON.toJSONString(daoUnit.execute(msg)));
        PoolFactory.getPool().destroyPool();
    } catch (Throwable e) {
        e.printStackTrace();
    }
}
Also used : UnitRequest(info.xiancloud.core.message.UnitRequest)

Aggregations

UnitRequest (info.xiancloud.core.message.UnitRequest)24 UnitResponse (info.xiancloud.core.message.UnitResponse)17 JSONObject (com.alibaba.fastjson.JSONObject)9 NotifyHandler (info.xiancloud.core.NotifyHandler)8 Unit (info.xiancloud.core.Unit)7 UnitMeta (info.xiancloud.core.UnitMeta)6 CacheGroup (info.xiancloud.cache.service.CacheGroup)5 Group (info.xiancloud.core.Group)5 Input (info.xiancloud.core.Input)5 JSONArray (com.alibaba.fastjson.JSONArray)4 Redis (info.xiancloud.cache.redis.Redis)4 CacheConfigBean (info.xiancloud.core.support.cache.CacheConfigBean)4 UnitInstance (info.xiancloud.core.distribution.service_discovery.UnitInstance)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 MessageType (info.xiancloud.core.distribution.MessageType)2 UnitOfflineException (info.xiancloud.core.distribution.exception.UnitOfflineException)2 UnitUndefinedException (info.xiancloud.core.distribution.exception.UnitUndefinedException)2 DefaultLocalAsyncSender (info.xiancloud.core.message.sender.local.DefaultLocalAsyncSender)2 ThreadPoolManager (info.xiancloud.core.thread_pool.ThreadPoolManager)2 LOG (info.xiancloud.core.util.LOG)2