1. 程式人生 > >spring boot http呼叫其他服務並解析

spring boot http呼叫其他服務並解析

新建一個maven專案


pom和 上一個一樣就行了,注意properties裡面多一個

#tomcat
server.port=8081

這樣我就直接把他埠改了--------瞬間整兒人就好了----

package ccy.consumer_movie;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@SpringBootApplication
public class StartMain {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}

public static void main(String[] args) {
SpringApplication.run(StartMain.class, args);
}
}

[email protected] 是建立一個bean  相當於以前的配置檔案 <bean> RestTemplate 這貨是傳送http的  整體感覺有點類似hibernate以前的JdbcTemplate注入,也是通過配置直接打到屬性的set方法上面 ----------------------

package ccy.consumer_movie.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


import ccy.consumer_movie.model.User;


@RestController
@RequestMapping("movieController")
public class MovieController {
@Autowired
private RestTemplate restTemplate;
/**
* http://localhost:8081/movieController/findById?id=1
* @param id
* @return
*/
@RequestMapping(value = "findById")
public User findById(Long id) {
System.out.println("--movieController-接到id--" + id);
String url="http://localhost:8080/userController/findById?id="+id;
User user=restTemplate.getForObject(url, User.class);
return user;
}
}

-----------------這裡面的RestTemplate 就是你剛才搞進去的,從IOC上取得,這裡要麼理解一下Spring的IOC,簡單來說就是個map,要麼就呵呵了,反正可以-----------------------

User user=restTemplate.getForObject(url, User.class); 這句話有很大的資訊量,

1.上一個專案會給你個json

1.返回的是個json能夠幫你自動映射出來

User類和上一個一模一樣就不說了

-------------------------------------------------------

通過(二) 和(三) 也就能夠 搭建簡單的SpringBoot以及對外訪問,對資料庫訪問 和 提供訪問資源了

後續開始整合springCloudy