概念
服務生產者:服務的被調用方(即:爲其他服務提供服務的服務)
服務消費者:服務的調用方(即:依賴其他服務的服務)
以微商城系統爲例:用戶發起購買商品請求,調用商品信息微服務是否滿足購買條件,如果滿足那就去查用戶信息,如下圖所示:
商品微服務是服務消費者,用戶微服務就是服務生產者。
接下來以“微商城”系統爲例,編寫服務生產者和消費者。
編寫一個服務生產者
第一步:通過start.spring.io構建服務生產者項目
打開地址:https://start.spring.io
如下圖所示,選擇相應信息:
增加Dependencies模塊支持:
1、web
2、jpa 訪問持久層
3、h2 內嵌數據庫(可以做一些數據的展示)
可以直接搜索添加即可,添加完成後點擊Generate the project,將會生產代碼的壓縮包,解壓導入idea開發工具即可。
第二步:編寫sql腳本
由於用的是內嵌h2數據庫,所以這裏編寫創建用戶表的sql腳本和數據:
schema.sql
drop table user if exists;
create table user(
id bigint generated by default as identity,
user_name varchar(40),
name varchar(20),
age int(3),
balance decimal(10,2),
primary key(id)
)
data.sql
insert into user(id,user_name,name,age,balance) values (1,'tangseng','唐僧',20,98.00);
insert into user(id,user_name,name,age,balance) values (2,'wukong','齊天大聖',18,10000.00);
insert into user(id,user_name,name,age,balance) values (3,'bajie','二師兄',25,898.00);
insert into user(id,user_name,name,age,balance) values (4,'wujing','三師弟',35,998.00);
第三步:application.ml配置文件
server:
port: 8080
spring:
spa:
generate-ddl: false
show-sql: true
hibernate:
ddl-auto: none
datasource:
platform: h2
schema: classpath:schema.sql
data: classpath:data.sql
logging:
level:
root: INFO
org.hibernate: INFO
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
com.itunion: DEBUG
第三步:編寫User實體類
@Entity
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String userName;
@Column
private String name;
@Column
private int age;
@Column
private BigDecimal balance;
......省略get/set方法
}
第四步:編寫UserRepository
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
}
這裏繼承了JpaRepository。
第五步:編寫UserController
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/simple/{id}")
public User findById(@PathVariable Long id){
User user = this.userRepository.getOne(id);
System.out.println(user.toString());
return user;
}
}
第六步:測試
瀏覽器輸入地址:http://127.0.0.1:8080/simple/2
{"id":2,"userName":"wukong","name":"齊天大聖","age":18,"balance":10000.00}
好了,到這裏一個簡單的微服務服務生產者已經編寫完成。
備註:代碼結構如下
編寫一個服務消費者
第一步:通過start.spring.io構建服務消費者項目
和上面步驟一樣,Artifact需要修改,如下圖所示:
增加Dependencies模塊支持:
1、web
只需要web就可以了,添加完成後點擊Generate the project,將會生產代碼的壓縮包,解壓導入idea開發工具。
第二步:編寫User實體類
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class User {
private Long id;
private String userName;
private String name;
private int age;
private BigDecimal balance;
......省略其他get/set方法
}
這裏只是做一個接收數據的映射,不需要jpa的註解。
第三步:編寫GoodsController
@RestController
public class GoodsController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/goods/{id}")
public User findById(@PathVariable Long id){
return this.restTemplate.getForObject("http://127.0.0.1:8080/simple/"+id,User.class);
}
}
根據傳入的id通過restTemplate的方式去查詢服務生產者獲取用戶信息。
第四步:配置application.yml文件
server:
port: 8081
第五步:啓動測試
服務生產者和消費者都需要啓動。
訪問服務消費者地址:http://127.0.0.1:8081/goods/2
報錯信息:
Description:
Field restTemplate in com.itunion.cloud.web.controller.GoodsController required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
錯誤原因:RestTemplate 未實例化,MicroserviceSimpleConsumerGoodsApplication增加RestTemplate實例化代碼
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
};
再次啓動並訪問:http://127.0.0.1:8081/goods/2
返回結果
{"id":2,"userName":"wukong","name":"齊天大聖","age":18,"balance":10000.00}
總結
簡單的服務生產者和服務消費者已經實現了,用戶在購買商品的時候調用服務消費者的goods接口,然後服務消費者通過RestTemplate調用服務生產者simple查詢用戶信息。
文中爲了快速實現生產者和消費者的關係,採取了一些硬編碼的方式,在實際分佈式架構中是不行的,不過沒關係後面我們慢慢來使項目更加健壯。
問題
1、生產者和消費者應用如何進行監控?並且也沒有畫板,啥指標都沒得。沒辦法監控系統壓力、QPS、內存、CPU和日活的可視化面板,是不是很low?
2、上面提到的硬編碼問題,微服務地址和端口都是固定的,在實際項目場景中每次地址發生變更都需要去修改代碼(如果用Docker容器化部署那就更酸爽了)。
3、負載均衡怎麼辦?
4、服務直接的容錯機制如何處理?
5、用戶的認證和授權呢?
6、應用發生故障,如何能夠進行問題追蹤快速定位?