Search in sources :

Example 1 with UnitRequest

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

the class AbstractAsyncForwarder method forward.

@Override
public void forward(String uri, String ip, String msgId, Map<String, String> header, String body) {
    LOG.debug("this method is running in the netty http server's io thread.");
    UnitRequest controllerRequest;
    try {
        controllerRequest = bodyParams(body, header);
    } catch (BadRequestException badRequestException) {
        LOG.warn(badRequestException);
        ServerResponseBean responseBean = new ServerResponseBean();
        responseBean.setMsgId(msgId);
        responseBean.setHttpContentType(HttpContentType.APPLICATION_JSON);
        responseBean.setResponseBody(UnitResponse.error(Group.CODE_BAD_REQUEST, null, badRequestException.getLocalizedMessage()).toVoJSONString());
        IServerResponder.singleton.response(responseBean);
        return;
    }
    RequestContext context = controllerRequest.getContext();
    URIBean uriBean = URIBean.create(uri);
    context.setUri(uri).setIp(ip).setHeader(header).setUnit(uriBean.getUnit()).setGroup(uriBean.getGroup()).setUriExtension(uriBean.getUriExtension()).setMsgId(msgId).setUriParameters(uriBean.getUriParameters());
    // uri parameters overwrite body parameters.
    controllerRequest.getArgMap().putAll(uriBean.getUriParameters());
    BaseController controller = IControllerMapping.getController(controllerRequest, new TransactionalNotifyHandler() {

        protected void handle(UnitResponse unitResponse) {
            if (unitResponse == null) {
                Throwable emptyOutputException = new RuntimeException("UnitResponse is not allowed to be null.");
                LOG.error(emptyOutputException);
                unitResponse = UnitResponse.exception(emptyOutputException);
            } else if (StringUtil.isEmpty(unitResponse.getCode())) {
                Throwable emptyOutputException = new RuntimeException("UnitResponse's code is not allowed to be empty: " + unitResponse);
                LOG.error(emptyOutputException);
                unitResponse = UnitResponse.exception(emptyOutputException);
            }
            ServerResponseBean responseBean = new ServerResponseBean();
            responseBean.setResponseBody(extractContext(unitResponse));
            responseBean.setMsgId(msgId);
            responseBean.setHttpContentType(unitResponse.getContext().getHttpContentType());
            IServerResponder.singleton.response(responseBean);
        }
    });
    ThreadPoolManager.execute(controller, msgId);
}
Also used : UnitRequest(info.xiancloud.core.message.UnitRequest) BaseController(info.xiancloud.gateway.executor.BaseController) UnitResponse(info.xiancloud.core.message.UnitResponse) BadRequestException(info.xiancloud.core.distribution.exception.BadRequestException) ServerResponseBean(info.xiancloud.gateway.server.ServerResponseBean) TransactionalNotifyHandler(info.xiancloud.gateway.handle.TransactionalNotifyHandler) RequestContext(info.xiancloud.core.message.RequestContext) URIBean(info.xiancloud.gateway.executor.URIBean)

Example 2 with UnitRequest

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

the class AppTransaction method rollbackAndCloseTogether.

public void rollbackAndCloseTogether() throws SQLException {
    // 发送远程请求,将其他数据库事务提交和关闭
    JSONArray clientIds = TransactionalCache.clear();
    if (clientIds != null) {
        for (int i = 0; i < clientIds.size(); i++) {
            final String clientId = clientIds.getString(i);
            if (!LocalNodeManager.LOCAL_NODE_ID.equals(clientId)) {
                UnitRequest request = UnitRequest.create(RollbackAndCloseTogetherUnit.class);
                request.getContext().setDestinationNodeId(clientId);
                LocalNodeManager.send(request, new NotifyHandler() {

                    protected void handle(UnitResponse unitResponse) {
                        LOG.info(clientId + "的事务已经回滚");
                    }
                });
            }
        }
    }
    // 回滚和关闭自己的数据库事务
    connection.rollback();
    connection.close();
    // 清除本地事务
    localTransMap.remove(transactionId);
}
Also used : UnitRequest(info.xiancloud.core.message.UnitRequest) UnitResponse(info.xiancloud.core.message.UnitResponse) JSONArray(com.alibaba.fastjson.JSONArray) NotifyHandler(info.xiancloud.core.NotifyHandler)

Example 3 with UnitRequest

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

the class UnitRequestTest method testGetList.

@Test
public void testGetList() {
    List<Integer> list = new UnitRequest(new JSONObject() {

        {
            put("yy", new int[] { 0, 1 });
        }
    }).getList("yy");
    Assert.assertTrue(list.get(0) == 0);
    Assert.assertTrue(list.get(1) == 1);
    List<Unit> unitList = new UnitRequest(new JSONObject() {

        {
            put("yy", new Unit[] { new UnitResponseTestUnit() });
        }
    }).getList("yy");
    Assert.assertTrue(unitList.get(0).getName().equals(new UnitResponseTestUnit().getName()));
    List<UnitProxy> proxyList = new UnitRequest(new JSONObject() {

        {
            put("yy", new String[] { new UnitResponseTestUnit().toJSONString() });
        }
    }).getList("yy", UnitProxy.class);
    Assert.assertTrue(proxyList.get(0).getName().equals(new UnitResponseTestUnit().getName()));
}
Also used : UnitResponseTestUnit(info.xiancloud.core.test.output_test.UnitResponseTestUnit) UnitRequest(info.xiancloud.core.message.UnitRequest) JSONObject(com.alibaba.fastjson.JSONObject) Unit(info.xiancloud.core.Unit) UnitResponseTestUnit(info.xiancloud.core.test.output_test.UnitResponseTestUnit) UnitProxy(info.xiancloud.core.distribution.UnitProxy) Test(org.junit.Test)

Example 4 with UnitRequest

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

the class TestIssueToken method main.

public static void main(String[] args) throws ClassNotFoundException {
    Class.forName(RedisStartup.class.getName());
    JSONObject body = new JSONObject().fluentPut("appId", "25874717e9b1807c5cfb66427f7d3c8da02ecfe4").fluentPut("appSecret", "fa090344347a2cb867833678754e461c36449dc2429e9ee228ddaf3bd1ac0330");
    UnitResponse o = new IssueAccessToken().execute(new UnitRequest().setArgMap(body));
    System.out.println(o);
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) UnitRequest(info.xiancloud.core.message.UnitRequest) UnitResponse(info.xiancloud.core.message.UnitResponse) IssueAccessToken(com.apifest.oauth20.unit.IssueAccessToken) RedisStartup(info.xiancloud.cache.startup.RedisStartup)

Example 5 with UnitRequest

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

the class NonblockingMqttCallBack method messageArrived.

@Override
public void messageArrived(String topicIgnored, MqttMessage message) throws Exception {
    try {
        /*第一个参数如果包含"."会被eclipse paho转为"/",所以,不要依赖这个参数!*/
        String msgFullStr = message.toString();
        JSONObject json = JSONObject.parseObject(msgFullStr);
        IdManager.makeSureMsgId(json);
        MessageType messageType = MessageType.getMessageType(json);
        switch(messageType) {
            case offline:
                LOG.info(String.format("离线广播: %s", json));
                break;
            case request:
                UnitRequest request = Reflection.toType(json, UnitRequest.class);
                logMqttFly(request, msgFullStr);
                String group = request.getContext().getGroup(), unit = request.getContext().getUnit();
                request.getContext().setFromRemote(true);
                ISequencer.build(group, unit, json).sequence(// run this runnable if succeeded.
                () -> new DefaultLocalAsyncSender(request, new NotifyHandler() {

                    protected void handle(UnitResponse unitResponse) {
                        LocalNodeManager.sendBack(unitResponse);
                    }
                }).send(), /*failed directly, call this handler*/
                new NotifyHandler() {

                    protected void handle(UnitResponse unitResponse) {
                        LocalNodeManager.sendBack(unitResponse);
                    }
                });
                break;
            case response:
                LOG.debug("ssid只在远程请求和响应时才会有值");
                UnitResponse response = Reflection.toType(json, UnitResponse.class);
                logMqttFly(response, msgFullStr);
                String ssid = response.getContext().getSsid();
                NotifyHandler handler = LocalNodeManager.handleMap.getIfPresent(ssid);
                LocalNodeManager.handleMap.invalidate(ssid);
                UnitResponse responseUnitResponse = UnitResponse.create(json);
                if (handler == null) {
                    LOG.error(String.format("ssid=%s的消息没有找到对应的notifyHandler!整个消息内容=%s,", ssid, json), new Throwable());
                    break;
                }
                try {
                    ThreadPoolManager.execute(() -> {
                        handler.callback(responseUnitResponse);
                    });
                } catch (RejectedExecutionException threadPoolAlreadyShutdown) {
                    LOG.info("线程池已关闭,这里使用临时线程执行任务,针对停服务时线程池已关闭的情况。");
                    new Thread(() -> handler.callback(responseUnitResponse)).start();
                }
                break;
            default:
                LOG.error("未知的mqtt消息类型:" + messageType, new RuntimeException());
        }
    } catch (Throwable e) {
        LOG.error(e);
    } finally {
        MsgIdHolder.clear();
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) UnitRequest(info.xiancloud.core.message.UnitRequest) UnitResponse(info.xiancloud.core.message.UnitResponse) NotifyHandler(info.xiancloud.core.NotifyHandler) DefaultLocalAsyncSender(info.xiancloud.core.message.sender.local.DefaultLocalAsyncSender) MessageType(info.xiancloud.core.distribution.MessageType) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

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