原始碼地址:https://gitee.com/fighter3/eshop-project.git
持續更新中……
在上一節裡,我們搭建了一個微服務專案的整體架構,並進行了版本控制。
接下來我們進一步來完善架構,引入SpringBoot
、MybatisPlus
等開發框架,來支撐具體業務的開發。
1、引入SpringBoot
我們在父專案統一管理引入的jar包的版本。
一般的SpringBoot專案是通過parent方式引入SpringBoott依賴,但是這樣一來就違背了單個pom只有一個parent標籤的標準。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
所以我們採用父專案中以depencyMangement方式引入spring-boot,子專案依賴parent父配置即可。
<!--使用properties統一管理版本-->
<properties>
<java.version>1.8</java.version>
<spring.boot.version>2.2.2.RELEASE</spring.boot.version>
</properties>
<!--統一管理專案依賴版本-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2、引入MybatisPlus
關於MybatisPlus的基本使用,基本使用可以檢視我的這篇部落格:SpringBoot學習筆記(十七:MyBatis-Plus )。
MybatisPlus的官方文件做的也很不錯,詳細瞭解可以直接檢視官方文件:https://mybatis.plus/
引入MybatisPlus依賴和MySQL驅動依賴:
<mybatis.plus.version>3.4.1</mybatis.plus.version>
<!--mybatis-plus依賴-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis.plus.version}</version>
</dependency>
<!--mybatis-plus程式碼生成器依賴-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis.plus.version}</version>
</dependency>
<!--模板引擎依賴,即使不需要生成模板,也需要引入-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
為了介面測試的方便,我們還引入了swagger2的增強工具knife4j
<!--knife4j依賴-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j-version}</version>
</dependency>
3、使用MP程式碼生成器
接下來我們以使用者模組為例,演示MybatisPlus程式碼生成器的使用。關於程式碼生成器的更多內容可以直接檢視官方文件:https://mybatis.plus/guide/generator.html
在上面我們已經引進行了統一的依賴版本管理,在子模組裡還需要引入依賴,不過可以免去版本號。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</dependency>
<!--模板引擎依賴,即使不需要生成模板,也需要引入-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
我們還引入了lombok用來簡化程式碼,使用lombok可以省去生成大量getter/setter程式碼。在Idea中使用需要安裝外掛,在外掛裡自行搜尋安裝即可。
- 由於程式碼生成器與業務無關,所以將程式碼生成類建在測試目錄下:
- 程式碼生成器類的相關程式碼
public class MySQLCodeGenerator {
/**
* <p>
* 讀取控制檯內容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請輸入正確的" + tip + "!");
}
public static void main(String[] args) {
// 程式碼生成器
AutoGenerator mpg = new AutoGenerator();
// 全域性配置
GlobalConfig gc = new GlobalConfig();
//設定專案位置,這裡直接設定為絕對路徑
String projectPath = "D:\\WorkSpace\\IdeaProjects\\eshop-project\\eshop-user";
//輸出目錄
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("三分惡");
gc.setOpen(false);
gc.setSwagger2(true); //實體屬性 Swagger2 註解
mpg.setGlobalConfig(gc);
// 資料來源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/shop_user?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
//包配置
PackageConfig pc = new PackageConfig();
//模組名配置
//pc.setModuleName(scanner("模組名"));
pc.setParent("cn.fighter3");
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
///策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("你自己的父類實體,沒有就不用設定!");
//【實體】是否為lombok模型
strategy.setEntityLombokModel(true);
//生成 @RestController 控制器
strategy.setRestControllerStyle(true);
// 公共父類
//strategy.setSuperControllerClass("你自己的父類控制器,沒有就不用設定!");
// 寫於父類中的公共欄位
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.execute();
}
}
MP的程式碼生成器支援很多配置,包括基本配置、資料配置、資料庫表配置等等。甚至可以自定義模板。具體可以檢視:https://mybatis.plus/config/generator-config.html#基本配置
- 生成程式碼很簡單,直接執行程式碼生成器類,輸入表名就行了
- 生成的程式碼如下:
4、基本業務程式碼編寫
接下來我們簡單地在使用者服務中編寫一個基本的檢視和增加的功能。
- 在resource目錄下新增配置檔案application.yml,寫入相關配置:
# 資料來源配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/shop_user?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8
username: root
password: root
- 在cn.fighter3包下手動建立啟動類EshopUserApplication.java:
@SpringBootApplication
@MapperScan("cn.fighter3.mapper")
public class EshopUserApplication {
public static void main(String[] args) {
SpringApplication.run(EshopUserApplication.class, args);
}
}
- 在pom.xml檔案中新增對common模組的依賴
<dependency>
<groupId>cn.fighter3</groupId>
<artifactId>eshop-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
- 在common工程中建立統一的結果返回類
/**
* @Author: 三分惡
* @Date: 2021/5/16
* @Description: 統一結果返回類
**/
@Data
@Builder
@AllArgsConstructor
public class CommonResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Tolerate
public CommonResult() {
}
private Integer code;
private String message;
private T data;
public static CommonResult ok() {
return CommonResult.builder().code(200).message("請求成功").build();
}
public static CommonResult ok(Object data) {
return CommonResult.builder().code(200).message("請求成功").data(data).build();
}
public static CommonResult error(String message) {
return CommonResult.builder().code(500).message("響應異常").build();
}
}
- 在ShopUserController.java中編寫相關介面的程式碼
/**
* <p>
* 使用者表 前端控制器
* </p>
*
* @author 三分惡
* @since 2021-05-16
*/
@RestController
@RequestMapping("/shop-user")
@Api(value = "使用者資訊介面", tags = "使用者介面")
public class ShopUserController {
@Autowired
private IShopUserService shopUserService;
@PostMapping("/user/add")
@ApiOperation(value = "新增使用者介面")
public CommonResult addUser(@RequestBody ShopUser shopUser) {
this.shopUserService.save(shopUser);
return CommonResult.ok();
}
@GetMapping("/user/get-by-id")
@ApiOperation(value = "根據id獲取使用者資訊介面")
public CommonResult getUserById(@RequestParam Integer id) {
ShopUser shopUser = this.shopUserService.getById(id);
return CommonResult.ok(shopUser);
}
}
執行啟動類,啟動專案,我們來看看執行的結果。
訪問 http://127.0.0.1:8080/doc.html ,我們可以看到knife4j介面文件頁面:
接下來測試一下我們的新增介面,可以看到請求成功,檢視資料庫表,發現也多了資料。
測試根據ID獲取使用者資訊介面:
5、小問題
在開發的過程中使用了一些Jdk1.8的語法,發現出現 Error:(66, 87) java: -source 1.5 中不支援方法引用 (請使用 -source 8 或更高版本以啟用方法引用)
,解決這個問題需要修改兩處:
- 在Idea中, 找到Build,Execution,Deployment >> Compiler >> Java Compiler ,把JDK版本改成8。
- 在Idea中, File->Project Structure,在source中將Language level 從5.0改為8。
好了,我們基本的業務開發到這就算是完成了,其它服務蕭規曹隨就行了。
"簡單的事情重複做,重複的事情認真做,認真的事情有創造性地做!"——
我是三分惡,可以叫我老三/三分/三哥/三子,一個能文能武的全棧開發,咱們下期見!
參考:
【1】小專欄 《SpringCloudAlibaba微服務實戰》
【2】:Spring Cloud Alibaba系列之-專案搭建(一)