為什么要進行微服務拆分?
在平常的商城項目中,我們一般的項目結構模塊都是將各種業務放在同一個項目文件夾,比如像:
用戶,購物車,商品,訂單,支付等業務都是放在一起,這樣很容易一個文件改動造成多個文件也要變動,而且在團隊項目中也不容易維護,所以可以進行微服務拆分,來解決這個問題。
怎么拆分?
從拆分目標來說,要做到:
- 高內聚:每個微服務的職責要盡量單一,包含的業務相互關聯度高、完整度高。
- 低耦合:每個微服務的功能要相對獨立,盡量減少對其它微服務的依賴。
從拆分方式來說,一般包含兩種方式:
- 縱向拆分:按照業務模塊來拆分
- 橫向拆分:抽取公共服務,提高復用性
對于hmall商城項目,它分為5大模塊:
- 用戶模塊
- 商品模塊
- 購物車模塊
- 訂單模塊
- 支付模塊
我這里采用的是橫向拆分,把它們公共的服務提取出來放在hm-api里面
比如在購物車模塊里面,它使用到了商品模塊里面的服務,
那么就可以把購物車模塊里面用到的商品模塊里面的服務抽取出來。
實現微服務拆分
前提:
IDEA(2021以上版本),JDK11,VMware Workstation Pro,MobaXterm
會使用docker,涉及到服務的遠程調用(這里使用的是nacos注冊中心)
項目架構:
hm-api:抽取出來的公共服務
用戶業務
新建項目:
從原本的單體商城項目中,把用戶模塊的內容復制過來,如圖:
這里還有很重要的是配置yaml文件
application.yaml
application-dev.yaml
application-local.yaml
在運行前,先配置一下UserApplication
連接上虛擬機,開啟MySQL和nacos
一些命令:
# 設置開機自啟systemctl enable docker#查看docker ps#啟動數據庫docker start mysql#訪問nacosdocker log -f nacos
運行成功:
同理,剩下的4個業務也是這樣拆分,其實公共服務就是把各個業務交織的部分,抽取出來,這樣就只需要在hm-api里面去調用就可以,
并且pom.xml里面要引入這個公共服務api
<!-- hm-api--><dependency><groupId>com.heima</groupId><artifactId>hm-api</artifactId><version>1.0.0</version></dependency>
hm-api
項目結構:
client:
package com.hmall.api.client;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;import java.util.List;
import java.util.Set;@FeignClient("cart-service")
public interface CartClient {@DeleteMapping("/carts")void deleteCartItemByIds(@RequestParam("ids") Set<Long> ids);
}
package com.hmall.api.client;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;import java.util.List;
import java.util.Set;@FeignClient("cart-service")
public interface CartClient {@DeleteMapping("/carts")void deleteCartItemByIds(@RequestParam("ids") Set<Long> ids);
}
package com.hmall.api.client;import io.swagger.annotations.ApiImplicitParam;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
@FeignClient("trade-service")
public interface TradeClient {@ApiImplicitParam(name = "orderId", value = "訂單id", paramType = "path")@PutMapping("/orders/{orderId}")void markOrderPaySuccess(@PathVariable("orderId") Long orderId);
}
package com.hmall.api.client;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("user-service")
public interface UserClient {@PutMapping("/users/money/deduct")public void deductMoney(@RequestParam("pw") String pw, @RequestParam("amount") Integer amount);
}
總結:
微服務架構,首先是服務化,就是將單體架構中的功能模塊從單體應用中拆分出來,獨立部署為多個服務。同時要滿足下面的一些特點:
-
單一職責:一個微服務負責一部分業務功能,并且其核心數據不依賴于其它模塊。
-
團隊自治:每個微服務都有自己獨立的開發、測試、發布、運維人員,團隊人員規模不超過10人
-
服務自治:每個微服務都獨立打包部署,訪問自己獨立的數據庫。并且要做好服務隔離,避免對其它服務產生影響