RPC和HTTP
無論是微服務還是SOA,都面臨着服務間的遠端調用。
常見的遠端調用方式有以下2種:
- RPC:Remote Produce Call遠端過程調用,類似的還有RMI(remote method invoke)。自定義資料格式,基于原生TCP通信,速度快,效率高。早期的webservice,現在熱門的dubbo,都是RPC的典型代表.
-
Http:http其實是一種網絡傳輸協定,基于TCP,規定了資料傳輸的格式。現在用戶端浏覽器與服務端通信基本都是采用Http協定,也可以用來進行遠端服務調用。缺點是消息封裝臃腫,優勢是對服務的提供和調用方沒有任何技術限定,自由靈活,更符合微服務理念。
現在熱門的Rest風格,就可以通過http協定來實作。
如果公司全部采用Java技術棧,那麼使用Dubbo作為微服務架構是一個不錯的選擇。
相反,如果公司的技術棧多樣化,而且你更青睐Spring家族,那麼SpringCloud搭建微服務是不二之選。在我們的項目中,我們會選擇SpringCloud套件,是以我們會使用Http方式來實作服務間調用。
代碼
首先在項目中注冊一個RestTemplate對象,可以在啟動類位置注冊:
@SpringBootApplication
public class HttpDemoApplication {
public static void main(String[] args) {
SpringApplication.run(HttpDemoApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
pojo:
package com.leyou.httpdemo.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
// 使用者名
private String userName;
// 密碼
private String password;
// 姓名
private String name;
// 年齡
private Integer age;
// 性别,1男性,2女性
private Integer sex;
// 出生日期
private Date birthday;
// 建立時間
private Date created;
// 更新時間
private Date updated;
// 備注
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password="
+ password + ", name=" + name + ", age=" + age + ", sex=" + sex
+ ", birthday=" + birthday + ", created=" + created
+ ", updated=" + updated + ", note=" + note + "]";
}
}
在測試類中直接@Autowired注入:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HttpDemoApplication.class)
public class HttpDemoApplicationTests {
@Autowired
private RestTemplate restTemplate;
@Test
public void httpGet() {
User user = this.restTemplate.getForObject("http://localhost/hello", User.class);
System.out.println(user);
}
}
通過RestTemplate的getForObject()方法,傳遞url位址及實體類的位元組碼,RestTemplate會自動發起請求,接收響應,并且幫我們對響應結果進行反序列化