有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpringWeb应用程序定期刷新数据

我目前正在开发一个网上银行应用程序,您可以在其中购买股票。它是用spring boot构建的,前端是html/css

我正在使用YahooFinance API获取股票报价,但我需要刷新页面以获取实时股票报价,如何每30秒自动更新页面以获取每只股票的新价格

还有,有没有一种方法可以使用线程来实现这一点

银行控制员

    @GetMapping("/banking/stocks")
public String stocks(Model model) {

    model.addAttribute("stock", new StockDto());
    try {
        List<Stock> stocks = stockService.getDefaultStocks();
        model.addAttribute("stocks", stocks);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return "stocks.html";
}

StockServiceImpl:

@Service
public class StockServiceImpl implements StockService {

private String[] startingStocks = { "AAPL", "BABA", "MSFT", "AXP", "BA", "AMD", "TSLA", "MA", "SHOP", "GOOGL",
        "KL" };

@Override
public Stock getStock(String stockName) throws IOException {
    Stock stock = YahooFinance.get(stockName);
    return stock;
}

@Override
public Map<String, Stock> getStock(String[] s) throws IOException {
    Map<String, Stock> stocks = YahooFinance.get(s);
    return stocks;
}

@Override
public List<Stock> getDefaultStocks() throws IOException {
     Map<String, Stock> stocks = YahooFinance.get(startingStocks);
     List<Stock> stockList = new ArrayList<Stock>();
     for(String s : startingStocks) {
         stockList.add(stocks.get(s));
     }
    return stockList;
}

}

用于显示股票的HTML页面:

<main class='main-content bgc-grey-100'>
        <div id='mainContent'>
            <div class="container-fluid">
                <br>
                <h4 class="c-grey-900 mT-10 mB-30">Stock Table</h4>
                <form action="#" th:object="${stock}" th:action="@{/banking/stock-search}"
                    method="POST" class="form-inline my-2 my-lg-0">
                    <input class="form-control mr-sm-2" type="search"
                        th:field="*{name}" placeholder="Search Stock"
                        aria-label="Search">
                    <button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
                </form>

                <br>
                <div 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>Trade</th>
                                        <th>Name</th>
                                        <th>Price</th>
                                        <th>(%) Change</th>
                                        <th>Div Yield (%)</th>
                                    </tr>
                                </thead>
                                <tfoot>
                                    <tr>
                                        <th>Ticker</th>
                                        <th>Trade</th>
                                        <th>Name</th>
                                        <th>Price</th>
                                        <th>(%) Change</th>
                                        <th>Div Yield (%)</th>
                                    </tr>
                                </tfoot>
                                <tbody>
                                    <tr th:each="stock : ${stocks}">
                                        <td th:text="${stock.getSymbol()}"></td>
                                            <td>
                                             <form action="#" th:action="@{/banking/stocks/} + ${stock.symbol}" method="get">
                                                 <button class="btn btn-outline-success my-2 my-sm-0" th:id="'table_entry_childs_button_' + ${stock.symbol}" type="submit">
                                                    <i>Trade</i>
                                                  </button>
                                             </form>
                                         </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>
    </main>

共 (2) 个答案

  1. # 1 楼答案

    您可以创建@Scheduled方法,该方法可以每隔30秒调用此API请求以获取数据并更新前端

    @Scheduled(fixedRate = 30000)
    public void updateStocksElement() {
      
      //Call your /banking/stocks rest endpoint    
    
    }
    

    https://spring.io/guides/gs/scheduling-tasks/

  2. # 2 楼答案

    您可以使用spring boot利用STOMP协议和web套接字。 供参考: https://www.baeldung.com/spring-websockets-send-message-to-user

    在后端,您可以使用

    @Autowired
    SimpMessagingTemplate messagetemplate;
    
    public void somemethod(String strParam){
     while (true){
        // build string or json whatever you need to send
        messagetemplate.convertAndSend("/blabla/blabla",strParam);
        Thread.sleep(30*1000);
     }
    

    }

    在前端,你必须使用跺脚。js

    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js"> 
    
    <script type="text/javascript">
    function load(){
       
       var stompClient = Stomp.client("ws://localhost:8080/ws");
       stompClient.connect({}, function (frame) {
        
           stompClient.subscribe('/blabla/blabla', function (message) {
             
            // do something here
           });
       });
    }
    
    最后,是html的一部分,您希望在加载时调用它
    <html>
      <body  onload="load()">
      </body>
    </html>