現有兩個微服務A和B,A負責管理使用者資訊,B負責角色管理。
(1)A服務發送請求,綁定角色,B服務收到請求後,調用A服務查詢使用者是否存在,判斷使用者是否重複綁定,條件通過則綁定使用者,最後回報資訊給A服務
(2)A服務發送請求擷取自己所有的權限,B服務收到請求後,調用A服務查詢使用者是否存在,存在則查詢資料回報資訊給A服務
上面兩個例子将使用者和角色進行解耦,兩者互相通信,那麼微服務與微服務之間如何實作互相通信,這裡将用一個簡單的例子來說明。
1、在B服務的controller中添加Rest方法,為A服務提供調用
@GetMapping(value = "/roles/getRoles/{userID}")
@Timed
public ResponseEntity getRolesByUserID(@PathVariable(value = "userID") Long userID){
log.debug("REST request to get Roles by UserID : {}", userID);
//這裡示範不做驗證,直接New一個 Role傳回Name
Role role = new Role();
role.setName("超級管理者");
return new ResponseEntity(role.getName(),HttpStatus.OK);
}
2、在A服務中聲明一個接口,在接口中添加B服務中Controller的Rest方法
@AuthorizedFeignClient(name = "b")
,指定與哪個微服務通信
import cn.netbank.cloud.app.client.AuthorizedFeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@AuthorizedFeignClient(name = "b")
public interface UserClient {
@GetMapping(value = "/api/roles/getRoles/{userID}")
String getRolesByUserID(@PathVariable(value = "userID") Long userID);
}
3、在A服務的Controller中注入
UserClient
@Resource
private UserClient userClient;
4、在A服務中的Controller的編寫Rest方法
@GetMapping(value = "/users/getRoles/{userID}")
@Timed
public ResponseEntity getRolesByUserID(@PathVariable(value ="userID") Long userID){
log.debug("REST request to Get Roles : {}", userID);
//調用接口中的方法
String roleName = userClient.getRolesByUserID(userID);
return new ResponseEntity(roleName,HttpStatus.OK);
}
5、在swagger ui中調試
原位址:https://www.zhengjie.me/blog/503.html