如何监听异步服务器端Java控制器?

时间:2018-04-11 04:39:39

标签: java angularjs spring asynchronous completable-future

谷歌搜索我遇到了很多例子,其中一个是来自Angular的$ q,以避免递归地命中我的服务器端以检查请求是否已完成数据。

我遇到了这个链接:Recursive $http.get in for loop

建议使用$ q,但我认为这不会解决我的问题。

JS:

function OrderFormController($scope, $http, $q) {

    $('#loaderImage').show();

    $http.get('/utilities/longProcess')
        .success(function(data, status, headers, config) {
            if(data != 'Still Processing'){
                console.log('Data from server');
                $scope.sampleJSON = data.pmdStructureWrapper;
                $scope.sampleJSONDuplicates = data.pmdDuplicates;
                $scope.$watch('sampleJSON', setTimeout(function() {
                    $('.panel-body li').each(function() {
                        if ($.trim($(this).text()) === "") {
                            $(this).hide();
                        }
                    });
                }, 1000));
            $('#loaderImage').hide();
            }else{
                console.log('rejected');
                $q.reject(data);
            }
        })
        .error(function(data, status, header, config) {

        });
}

控制器:

@RequestMapping("/utilities/longProcess")
public CompletableFuture<String> asyncLongProcess(HttpServletResponse response, HttpServletRequest request) {
    HttpSession session = request.getSession();
    return CompletableFuture.supplyAsync(() -> session.getAttribute("CACHED_RESULT"))
            .thenComposeAsync(obj -> {
                if (obj == null) {
                    if(session.getAttribute("BACKGROUND_PROCESSING") == null) {
                        session.setAttribute("BACKGROUND_PROCESSING", true);
                        CompletableFuture.supplyAsync(() -> callURL(response, request))
                                .thenAccept(result -> session.setAttribute("CACHED_RESULT", result));
                    }
                    return CompletableFuture.completedFuture("Still Processing");
                }

                return CompletableFuture.completedFuture(obj.toString());
            });
}

HTML:

<body ng-app ng-controller="OrderFormController">
<header>
    <div class="container">
        <div id="branding">
            <h1><span class="highlight">Review  </span> Result</h1>
            <form class="form-logout" role="form" action="/logout">
                <input type="submit" value="Logout" id="logout" class="btn btn-primary btn-lg pull-right">
            </form>
        </div>

    </div>
</header>

<img src="../img/spinner.gif" id="loaderImage" style='display:none'>
<div class="col-md-12 col-lg-12" ng-cloak="">
    <div class="panel with-nav-tabs panel-default">
        <div class="panel-heading">
            <ul class="nav nav-tabs">
                <li class="active"><a href="#tab1default" data-toggle="tab">Classes</a></li>
                <li><a href="#tab2default" data-toggle="tab">Triggers</a></li>
                <li><a href="#tab3default" data-toggle="tab">Visualforce pages</a></li>
                <li><a href="#tab4default" data-toggle="tab">Duplicate Codes</a></li>
            </ul>
        </div>
        <div class="panel-body">
            <div class="tab-content">
                <div class="tab-pane fade in active" id="tab1default">
                    <ul class="col-md-12 col-lg-12">
                        <li ng-click="showErrorDetails(key)" class="col-sm-12 col-md-4 col-lg-4 eachClassCell"
                            ng-repeat='(key,value) in sampleJSON'>
                            <div ng-if="key.indexOf('.cls') > -1">
                                <div title="{{key}}" class="classNameLabel">{{key}}</div>
                                <div title="Error count" class="errorContainer">
                                    <span class="errorCount">{{value.pmdStructures.length}}</span>
                                    <span class="errorMeter"
                                          ng-repeat="eachClass in value.pmdStructures | limitTo: 10"></span>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
                <div class="tab-pane fade" id="tab2default">
                    <ul class="col-md-12 col-lg-12">
                        <li ng-click="showErrorDetails(key)" class="col-sm-12 col-md-4 col-lg-4 eachClassCell"
                            ng-repeat='(key,value) in sampleJSON'>
                            <div ng-if="key.indexOf('.trigger') > -1">
                                <div title="{{key}}" class="classNameLabel">{{key}}</div>
                                <div title="Error count" class="errorContainer">
                                    <span class="errorCount">{{value.pmdStructures.length}}</span>
                                    <span class="errorMeter"
                                          ng-repeat="eachClass in value.pmdStructures | limitTo: 10"></span>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
                <div class="tab-pane fade" id="tab3default">
                    <ul class="col-md-12 col-lg-12">
                        <li ng-click="showErrorDetails(key)" class="col-sm-12 col-md-4 col-lg-4 eachClassCell"
                            ng-repeat='(key,value) in sampleJSON'>
                            <div ng-if="key.indexOf('.page') > -1">
                                <div title="{{key}}" class="classNameLabel">{{key}}</div>
                                <div title="Error count" class="errorContainer">
                                    <span class="errorCount">{{value.pmdStructures.length}}</span>
                                    <span class="errorMeter"
                                          ng-repeat="eachClass in value.pmdStructures | limitTo: 10"></span>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
                <div class="tab-pane fade" id="tab4default">
                    <ul class="col-md-12 col-lg-12">
                        <li ng-click="showDuplicateDetails(eachValue)" class="col-sm-12 col-md-4 col-lg-4 eachClassCell"
                            ng-repeat='eachValue in sampleJSONDuplicates'>
                            <div title="{{eachValue.duplicationInFile}}" class="classNameLabel">
                                {{eachValue.duplicationInFile}}
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
<form>


</form>
<footer>
    <p>Salesforce Free Code Review, Copyright &copy; 2017</p>
    </p>
</footer>
<script type="application/javascript">


</script>
</body>

这样做是为了避免超时,它向客户端发送Still Processing消息,因为超时限制为30000ms, 我知道我想到的第一件事就是每次请求都要做一个延迟加载大约30个数据,但请相信我,我不能。

我已经构建了一个代码审查工具,因此当URL被点击时,它会在所有具有后台线程的类上运行代码审查,然后在大约120-150秒之后在CompletableFuture中返回响应。在页面再次刷新之前,客户端不知道此响应。

即使刷新页面后,由于数据超过7MB,页面显示结果大约需要13-35秒。

代码在我的本地工作正常,但当我在heroku(共享服务器)中托管时,我开始超时。 有两个问题:

1)angularJS如何检测RestAPI响应的变化?(因为会发送两个响应,首先是“Still Processing”,第二个是真实结果。这是我必须消耗的。) / p>

2)如何从Controller中延迟加载已经采用JSON格式的数据?

enter image description here

更新1:

我也尝试使用OutputStream:

控制器:

@RequestMapping("/utilities/longProcessStream")
public StreamingResponseBody asyncLongProcessStream(HttpServletResponse response, HttpServletRequest request) {
    return new StreamingResponseBody() {
        @Override
        public void writeTo(OutputStream outputStream) throws IOException {
            PMDController.this.callURL(response, request, outputStream);
        }
    };
}

但是现在响应更改为XML并且不打印JS console.log('Data from server');行,直到从服务器端收集完整响应。

当响应更改为XML时,我如何将其解析为JSON格式,因为我的完整JS依赖于JSON?

完成请求完成后,为什么角度显示结果?

1 个答案:

答案 0 :(得分:0)

我找到了一个读取StreamingBodyResponse的库,它们在内部将blob类型更改为JSON,这正是我所需要的:

@RequestMapping("/utilities/longProcessStream")
public StreamingResponseBody asyncLongProcessStream(HttpServletResponse response, HttpServletRequest request) {
    response.addHeader("Content-Type", MediaType.APPLICATION_JSON);
    return new StreamingResponseBody() {
        @Override
        public void writeTo(OutputStream outputStream) throws IOException {
            PMDController.this.callURL(response, request, outputStream);
        }
    };
}

JS:

$('#loaderImage').show();

$scope.sampleJSONClass = {};
$scope.sampleJSONTrigger = {};
$scope.sampleJSONPages = {};
oboe('/utilities/longProcessStream')
    .done(function(data) {
        var dataFromServer = data.pmdStructureWrapper;
        if (Object.keys(dataFromServer)[0].endsWith('.cls')) {
            $scope.sampleJSONClass[Object.keys(dataFromServer)[0]] = Object.values(dataFromServer)[0];
        }
        if (Object.keys(dataFromServer)[0].endsWith('.trigger')) {
            $scope.sampleJSONTrigger[Object.keys(dataFromServer)[0]] = Object.values(dataFromServer)[0];
        }
        if (Object.keys(dataFromServer)[0].endsWith('.page')) {
            $scope.sampleJSONPages[Object.keys(dataFromServer)[0]] = Object.values(dataFromServer)[0];
        }
        $scope.$apply();
        $('#loaderImage').hide();
    })
    .fail(function() {
        console.log('error');
    });

这完美无缺。