首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Web App -定期刷新数据

Spring Web App -定期刷新数据
EN

Stack Overflow用户
提问于 2020-11-13 16:05:31
回答 2查看 132关注 0票数 0

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

我正在使用YahooFinance应用编程接口获取股票报价,但我需要刷新页面才能获得实时股票报价,如何每30秒自动更新页面以获取每只股票的新价格?

另外,有没有一种方法可以用Thread来实现呢?

银行业务控制器

代码语言:javascript
复制
    @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:

代码语言:javascript
复制
@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页面:

代码语言:javascript
复制
<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>
EN

回答 2

Stack Overflow用户

发布于 2020-11-13 19:00:40

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

在后端,您可以使用

代码语言:javascript
复制
@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);
 }

}

在前端,你必须使用stomp.js

代码语言:javascript
复制
<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
       });
   });
}
代码语言:javascript
复制
lastly, part of html where you want to call on load    
代码语言:javascript
复制
<html>
  <body  onload="load()">
  </body>
</html>
票数 0
EN

Stack Overflow用户

发布于 2020-11-13 21:37:16

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

代码语言:javascript
复制
@Scheduled(fixedRate = 30000)
public void updateStocksElement() {
  
  //Call your /banking/stocks rest endpoint    

}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64817398

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档