springwebsockets-订阅和检索数据

8tntrjer  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(206)

我正在开发一个股票交易应用程序,用户可以将股票列表保存到数据库中,当他们登录到webapp时,它将加载所有股票。
我正在尝试使用websockets和spring来调用yahoofinance api,以获得实时的股票价格。
我对stomp和websockets还比较陌生,所以这部分程序现在不起作用。
我希望这样当一个用户访问/股票,它将加载所有他们的股票,并附加到一个列表,但它更新每800毫秒每种股票的价格。

@Configuration
 @EnableWebSocketMessageBroker
 public class WebSocketConfig extends 
    AbstractWebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic");
    registry.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/stocks").withSockJS();
}

}

将数据传递到前端的银行控制器代码:

@GetMapping("/banking/stocks")
public String stocks(Model model) throws NoSuchMethodException, IOException {

    model.addAttribute("stock", new StockDto());

    List<Stock> stocks = stockService.getDefaultStocks(getCurrentUser());
    model.addAttribute("stocks", stocks);

    return "stocks.html";
}

@Scheduled(fixedRate = 8000)
public void retrieveData() throws Exception {
    List<UserDetails> principals = getAllPrincipals();

    for (UserDetails u : principals) {
        User user = userService.findByUsername(u.getUsername());
        List<Security> securities = securityService.findAllByUser_AccountNumber(user.getAccountNumber());
        simpMessagingTemplate.convertAndSend(DESTINATION,securities);
    }
}

股票.html:

<script type="text/javascript">
    var stompClient = null;
    var topic = null;

    function connect() {

        var socket = new SockJS("/app/stocks");
        stompClient = Stomp.over(socket);

        stompClient.connect({}, function(frame) {

            setConnected(true);

            stompClient.subscribe("/topic/stocks", function(retrieveData) {

                display(retrieveData.body);
            });
        })
    }

    function disconnect() {
        stompClient.disconnect();
        setConnected(false);
        console.log("Disconnected from stomp client!")
    }

    function setConnected(connected) {
        document.getElementById("connect").disabled = connected;
        document.getElementById("disconnect").disabled = !connect;
    }

    function display(message) {
        if (message) {
            var stockList = JSON.parse(message).getStocks;
            var table = document.createElement('table');
            var tableBody = document.getElementById('stockBody');

            for (var i = 0; i < stockList.length; i++) {
                var tr = document.createElement('tr');
                for (var j = 0; j < 4; j++) {
                    var td = document.createElement("td");
                    td.innerHTML = stockList.get(i).getPrice();
                }
            }
        }
    }
</script>

在身体内部:

<div>
                    <button id="connect" onclick="connect();">Connect</button>
                    <button id="disconnect" disabled="disabled"
                        onclick="disconnect();">Disconnect</button>
                </div>

                <br>
                <div id="stocklist" class="row">
                    <div class="col-md-12">
                        <div class="bgc-white bd bdrs-3 p-20 mB-20">
                            <table id="dataTable" class="table table-striped table-bordered"
                                cellspacing="0" width="100%">
                                <thead>
                                    <tr>
                                        <th>Ticker</th>
                                        <th>Options</th>
                                        <th>Name</th>
                                        <th>Price</th>
                                        <th>(%) Change</th>
                                        <th>Div Yield (%)</th>
                                    </tr>
                                </thead>
                                <tfoot>
                                    <tr>
                                        <th>Ticker</th>
                                        <th>Options</th>
                                        <th>Name</th>
                                        <th>Price</th>
                                        <th>(%) Change</th>
                                        <th>Div Yield (%)</th>
                                    </tr>
                                </tfoot>
                                <tbody id="stockBody">
                                    <tr th:each="stock : ${stocks}">

                                        <td th:text="'$'+${stock.getSymbol()}"></td>

                                        <td>
                                            <div class="container">
                                                <div class="row">
                                                    <div class=" center-block text-center">
                                                        <div class="btn-group text-center">

                                                            <form action="#"
                                                                th:action="@{/banking/stocks/} + ${stock.symbol}"
                                                                method="get">
                                                                <button class="btn btn-group btn-outline-success mr-3 "
                                                                    th:id="'table_entry_childs_button_' + ${stock.symbol}"
                                                                    type="submit">
                                                                    <i>Trade</i>
                                                                </button>
                                                            </form>

                                                            <form action="#"
                                                                th:action="@{/banking/stocks/removeUserStockTicker/} + ${stock.symbol}"
                                                                method="POST">
                                                                <button type="submit"
                                                                    class="btn  btn-group btn-danger btn-sm">
                                                                    <i class="fa fa-minus"></i>
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td th:text="${stock.getName()}"></td>
                                        <td th:text="${stock.getQuote().getPrice()}"></td>
                                        <td
                                            th:class="${stock.getQuote().getChangeInPercent() > 0 ? 'text-success' : 'text-danger'}"
                                            th:text="${stock.getQuote().getChangeInPercent() + '%'} "></td>
                                        <td th:if="${stock.getDividend().getAnnualYield() != null}"
                                            th:text="${stock.getDividend().getAnnualYield() + '%'}">0.00%</td>
                                        <td th:if="${stock.getDividend().getAnnualYield() == null}">0.00%</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

当我单击“连接”时,在我的google控制台上,我得到一个错误:

Opening Web Socket...
GET http://localhost:8080/app/stocks/info 404
Whoops! Lost connection to undefined

我需要股票清单被传递到前端,使其更新,而不是必须不断刷新页面。我已经为此工作了一段时间,如果能得到一些帮助就太好了。谢谢!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题