1. 程式人生 > >java springboot b2b2c shop 多使用者商城系統原始碼 (十六)用restTemplate消費服務

java springboot b2b2c shop 多使用者商城系統原始碼 (十六)用restTemplate消費服務

構架工程

建立一個springboot工程,去消費RESTFUL的服務。這個服務是 http:///gturnquist-quoters.cfapps.io/api/random ,它會隨機返回Json字串。 
在Spring專案中,它提供了一個非常簡便的類,叫RestTemplate,它可以很簡便的消費服務。

消費服務

通過RestTemplate消費服務,需要先context中註冊一個RestTemplate bean。程式碼如下:

複製程式碼
@Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
 
    @Bean
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        return args -> {
            String quote = restTemplate.getForObject(
                    "http://gturnquist-quoters.cfapps.io/api/random", String.class);
            log.info(quote.toString());
        };
    }
複製程式碼

執行程式,控制檯列印:

複製程式碼
{
“type”: “success”,
“value”: {
“id”: 6,
“quote”: “It embraces convention over configuration, providing an experience on par with frameworks that excel at early stage development, such as Ruby on Rails.”
}
}
複製程式碼

架構程式碼如下 :

 

"分散式b2b <wbr 完整專案的原始碼來源 Spring Cloud大型企業分散式微服務雲構建的B2B2C電子商務平臺原始碼請加企鵝求求: 一零叄八七七四六貳六