1、介绍

  • 我们会使用一个Dept部门模块做一个微服务通用案例Consumer消费者(Client)通过REST调用Provider提供者(Server)提供的服务。
  • 回顾Spring,SpringMVC,Mybatis等以往学习的知识。
  • Maven的分包分模块架构复习。

一个父工程带着多个Moudule子模块

MicroServiceCloud父工程(Project)下初次带着3个子模块(Module)

  • microservicecloud-api 【封装的整体entity/接口/公共配置等】
  • microservicecloud-consumer-dept-80 【服务提供者】
  • microservicecloud-provider-dept-8001 【服务消费者】

2、新建三个数据库

SpringCloud04:SpringCloud Rest学习环境搭建 - 图1

SpringCloud04:SpringCloud Rest学习环境搭建 - 图2.

SpringCloud04:SpringCloud Rest学习环境搭建 - 图3.

SpringCloud04:SpringCloud Rest学习环境搭建 - 图4.

  1. -- springcloud-db01
  2. -- begin
  3. CREATE DATABASE IF NOT EXISTS `springcloud-db01`;
  4. USE `springcloud-db01`;
  5. CREATE TABLE IF NOT EXISTS `dept` (
  6. `deptno` int NOT NULL AUTO_INCREMENT,
  7. `dname` varchar(50) NOT NULL DEFAULT '',
  8. `db_source` varchar(50) NOT NULL DEFAULT '',
  9. PRIMARY KEY (`deptno`)
  10. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='部门表';
  11. INSERT INTO `dept` (`deptno`, `dname`, `db_source`) VALUES
  12. (1, '开发部', 'db01'),
  13. (2, '财务部', 'db01'),
  14. (3, '人事部', 'db01'),
  15. (4, '市场部', 'db01'),
  16. (5, '运维部', 'db01');
  17. -- end
  18. -- springcloud-db02
  19. -- begin
  20. CREATE DATABASE IF NOT EXISTS `springcloud-db02`;
  21. USE `springcloud-db02`;
  22. CREATE TABLE IF NOT EXISTS `dept` (
  23. `deptno` int NOT NULL AUTO_INCREMENT,
  24. `dname` varchar(50) NOT NULL DEFAULT '',
  25. `db_source` varchar(50) NOT NULL DEFAULT '',
  26. PRIMARY KEY (`deptno`)
  27. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='部门表';
  28. INSERT INTO `dept` (`deptno`, `dname`, `db_source`) VALUES
  29. (1, '开发部', 'db02'),
  30. (2, '财务部', 'db02'),
  31. (3, '人事部', 'db02'),
  32. (4, '市场部', 'db02'),
  33. (5, '运维部', 'db02');
  34. -- end
  35. -- springcloud-db03
  36. -- begin
  37. CREATE DATABASE IF NOT EXISTS `springcloud-db03`;
  38. USE `springcloud-db03`;
  39. CREATE TABLE IF NOT EXISTS `dept` (
  40. `deptno` int NOT NULL AUTO_INCREMENT,
  41. `dname` varchar(50) NOT NULL DEFAULT '',
  42. `db_source` varchar(50) NOT NULL DEFAULT '',
  43. PRIMARY KEY (`deptno`)
  44. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='部门表';
  45. INSERT INTO `dept` (`deptno`, `dname`, `db_source`) VALUES
  46. (1, '开发部', 'db03'),
  47. (2, '财务部', 'db03'),
  48. (3, '人事部', 'db03'),
  49. (4, '市场部', 'db03'),
  50. (5, '运维部', 'db03');
  51. -- end

3、创建父工程

  • 新建父工程项目springcloud,切记packaging是pom模式
  • 主要是定义POM文件,将后续各个子模块公用的jar包等统一提取出来,类似一个抽象父类

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.godfrey</groupId>
  7. <artifactId>spring-cloud-study</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <packaging>pom</packaging>
  10. <properties>
  11. <maven.compiler.source>1.8</maven.compiler.source>
  12. <maven.compiler.target>8</maven.compiler.target>
  13. <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
  14. <spring-boot.version>2.3.5.RELEASE</spring-boot.version>
  15. <mysql.version>8.0.22</mysql.version>
  16. <druid.version>1.1.23</druid.version>
  17. <mybatis.version>1.3.2</mybatis.version>
  18. <lombok.version>1.18.16</lombok.version>
  19. </properties>
  20. <dependencyManagement>
  21. <dependencies>
  22. <!--springCloud的依赖-->
  23. <dependency>
  24. <groupId>org.springframework.cloud</groupId>
  25. <artifactId>spring-cloud-dependencies</artifactId>
  26. <version>${spring-cloud.version}</version>
  27. <type>pom</type>
  28. <scope>import</scope>
  29. </dependency>
  30. <!--SpringBoot-->
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-dependencies</artifactId>
  34. <version>${spring-boot.version}</version>
  35. <type>pom</type>
  36. <scope>import</scope>
  37. </dependency>
  38. <!--数据库-->
  39. <dependency>
  40. <groupId>mysql</groupId>
  41. <artifactId>mysql-connector-java</artifactId>
  42. <version>${mysql.version}</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>com.alibaba</groupId>
  46. <artifactId>druid</artifactId>
  47. <version>${druid.version}</version>
  48. </dependency>
  49. <!--Mybatis 启动器-->
  50. <dependency>
  51. <groupId>org.mybatis.spring.boot</groupId>
  52. <artifactId>mybatis-spring-boot-starter</artifactId>
  53. <version>${mybatis.version}</version>
  54. </dependency>
  55. <!--Lombok-->
  56. <dependency>
  57. <groupId>org.projectlombok</groupId>
  58. <artifactId>lombok</artifactId>
  59. <version>${lombok.version}</version>
  60. </dependency>
  61. </dependencies>
  62. </dependencyManagement>
  63. </project>

4、新建springcloud-api模块

4.1 pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>spring-cloud-study</artifactId>
  7. <groupId>com.godfrey</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>springcloud-api</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.projectlombok</groupId>
  15. <artifactId>lombok</artifactId>
  16. </dependency>
  17. </dependencies>
  18. </project>

4.2 在com.godfrey.springcloud.pojo包下,新建实体类Dept

  1. package com.godfrey.springcloud.pojo;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. import lombok.experimental.Accessors;
  5. import java.io.Serializable;
  6. @Data
  7. @NoArgsConstructor
  8. @Accessors(chain = true)
  9. public class Dept implements Serializable {
  10. private Long deptno;
  11. private String dname;
  12. private String db_source;
  13. public Dept(String dname) {
  14. this.dname = dname;
  15. }
  16. }

5、新建服务提供者springcloud-provider-dept-8001模块

5.1 pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>spring-cloud-study</artifactId>
  7. <groupId>com.godfrey</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>springcloud-provider-dept-8001</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>com.godfrey</groupId>
  15. <artifactId>springcloud-api</artifactId>
  16. <version>1.0-SNAPSHOT</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>mysql</groupId>
  20. <artifactId>mysql-connector-java</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>com.alibaba</groupId>
  24. <artifactId>druid</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.mybatis.spring.boot</groupId>
  28. <artifactId>mybatis-spring-boot-starter</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-web</artifactId>
  33. </dependency>
  34. </dependencies>
  35. </project>

5.2 配置文件application.yml

  1. server:
  2. port: 8001
  3. # mybatis的配置
  4. mybatis:
  5. type-aliases-package: com.godfrey.springcloud.pojo
  6. config-location: classpath:mybatis/mybatis-config.xml
  7. mapper-locations: classpath:mybatis/mapper/*.xml
  8. # spring的配置
  9. spring:
  10. application:
  11. name: springcloud-provider-dept
  12. datasource:
  13. type: com.alibaba.druid.pool.DruidDataSource #数据库
  14. driver-class-name: com.mysql.jdbc.Driver
  15. url: jdbc:mysql://localhost:3306/springcloud-db01?serverTimezone=GMT%2B8
  16. username: root
  17. password: root123

在resources目录下Mybatis配置文件,开启耳机缓存,mybatis.config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <setting name="cacheEnabled" value="true"/>
  8. </settings>
  9. </configuration>

接下来,新建项目结构

SpringCloud04:SpringCloud Rest学习环境搭建 - 图5.

5.3 DeptMapper

  1. package com.godfrey.springcloud.mapper;
  2. import com.godfrey.springcloud.pojo.Dept;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.springframework.stereotype.Repository;
  5. import java.util.List;
  6. /**
  7. * @author godfrey
  8. * @since 2020-11-16
  9. */
  10. @Mapper
  11. @Repository
  12. public interface DeptMapper {
  13. boolean addDept(Dept dept);
  14. Dept queryById(Long id);
  15. List<Dept> queryAll();
  16. }

DeptMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.godfrey.springcloud.mapper.DeptMapper">
  6. <insert id="addDept" parameterType="Dept">
  7. insert into dept (deptno, dname, db_source)
  8. values (#{dname}, DATABASE())
  9. </insert>
  10. <select id="queryById" resultType="com.godfrey.springcloud.pojo.Dept" parameterType="Long">
  11. select *
  12. from dept
  13. where deptno = #{deptno};
  14. </select>
  15. <select id="queryAll" resultType="Dept">
  16. select *
  17. from dept;
  18. </select>
  19. </mapper>

5.4 DeptService

  1. package com.godfrey.springcloud.service;
  2. import com.godfrey.springcloud.pojo.Dept;
  3. import java.util.List;
  4. /**
  5. * @author godfrey
  6. * @since 2020-11-16
  7. */
  8. public interface DeptService {
  9. /**
  10. * 增加部门
  11. *
  12. * @return boolean
  13. */
  14. boolean addDept(Dept dept);
  15. /**
  16. * 通过id查询部门
  17. *
  18. * @return Dept
  19. */
  20. Dept queryById(Long id);
  21. /**
  22. * 查询所有部门
  23. *
  24. * @return java.util.List<com.godfrey.springcloud.pojo.Dept>
  25. */
  26. List<Dept> queryAll();
  27. }

5.5 DeptController

  1. package com.godfrey.springcloud.controller;
  2. import com.godfrey.springcloud.pojo.Dept;
  3. import com.godfrey.springcloud.service.DeptService;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import java.util.List;
  9. /**
  10. * @author godfrey
  11. * @since 2020-11-16
  12. */
  13. @RestController
  14. public class DeptController {
  15. private final DeptService deptService;
  16. public DeptController(DeptService deptService) {
  17. this.deptService = deptService;
  18. }
  19. @PostMapping("/dept/add")
  20. public boolean addDept(Dept dept) {
  21. return deptService.addDept(dept);
  22. }
  23. @GetMapping("/dept/get/{id}")
  24. public Dept queryById(@PathVariable("id") Long id) {
  25. Dept dept = deptService.queryById(id);
  26. if (dept == null) {
  27. throw new RuntimeException("Fail");
  28. }
  29. return dept;
  30. }
  31. @GetMapping("/dept/list")
  32. public List<Dept> queryAll() {
  33. return deptService.queryAll();
  34. }
  35. }

5.6 启动类

  1. package com.godfrey.springcloud;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class DeptProvider_8001 {
  6. public static void main(String[] args) {
  7. SpringApplication.run(DeptProvider_8001.class, args);
  8. }
  9. }

6、新建消费者springcloud-consumer-dept-80模块

6.1 pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>spring-cloud-study</artifactId>
  7. <groupId>com.godfrey</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>springcloud-consumer-dept-80</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>com.godfrey</groupId>
  15. <artifactId>springcloud-api</artifactId>
  16. <version>1.0-SNAPSHOT</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-web</artifactId>
  21. </dependency>
  22. </dependencies>
  23. </project>

6.2 配置文件application.yml

  1. server:
  2. port: 80

接下来,新建项目结构

SpringCloud04:SpringCloud Rest学习环境搭建 - 图6.

6.3 配置类ConfigBean

  1. package com.godfrey.springcloud.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.client.RestTemplate;
  5. /**
  6. * 配置类
  7. *
  8. * @author godfrey
  9. * @since 2020-11-18
  10. */
  11. @Configuration
  12. public class ConfigBean {
  13. @Bean
  14. public RestTemplate getRestTemplate() {
  15. return new RestTemplate();
  16. }
  17. }

6.4 DeptConsumerController

  1. package com.godfrey.springcloud.controller;
  2. import com.godfrey.springcloud.pojo.Dept;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.PostMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import org.springframework.web.client.RestTemplate;
  9. import java.util.List;
  10. import java.util.concurrent.atomic.AtomicInteger;
  11. /**
  12. * @author godfrey
  13. * @since 2020-11-18
  14. */
  15. @RestController
  16. public class DeptConsumerController {
  17. private RestTemplate restTemplate;
  18. private static final String REST_URL_PREFIX = "http://localhost:800";
  19. @Autowired
  20. DeptConsumerController(RestTemplate restTemplate) {
  21. this.restTemplate = restTemplate;
  22. }
  23. @PostMapping("/consumer/dept/add")
  24. public boolean addDept(Dept dept) {
  25. return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add/", dept, Boolean.class);
  26. }
  27. @RequestMapping("/consumer/dept/get/{id}")
  28. public Dept queryById(@PathVariable("id") Long id) {
  29. return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class);
  30. }
  31. @RequestMapping("/consumer/dept/list")
  32. public List<Dept> queryAll() {
  33. return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
  34. }
  35. }

6.5 启动类

  1. package com.godfrey.springcloud;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class DeptConsumer_80 {
  6. public static void main(String[] args) {
  7. SpringApplication.run(DeptConsumer_80.class, args);
  8. }
  9. }

7、测试

服务提供者:

SpringCloud04:SpringCloud Rest学习环境搭建 - 图7

服务消费者

SpringCloud04:SpringCloud Rest学习环境搭建 - 图8

8、集群

根据springcloud-provider-dept-8001模块,新建两个模块springcloud-provider-dept-8002和springcloud-provider-dept-8003即可,随后修改相应的配置文件和接口即可

为了使消费者轮询访问8001~3,springcloud-consumer-dept-80模块下controller修改为如下:

  1. package com.godfrey.springcloud.controller;
  2. import com.godfrey.springcloud.pojo.Dept;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.PostMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import org.springframework.web.client.RestTemplate;
  9. import java.util.List;
  10. import java.util.concurrent.atomic.AtomicInteger;
  11. /**
  12. * @author godfrey
  13. * @since 2020-11-18
  14. */
  15. @RestController
  16. public class DeptConsumerController {
  17. private RestTemplate restTemplate;
  18. private static final String REST_URL_PREFIX = "http://localhost:800";
  19. private AtomicInteger num = new AtomicInteger(3);
  20. @Autowired
  21. DeptConsumerController(RestTemplate restTemplate) {
  22. this.restTemplate = restTemplate;
  23. }
  24. @PostMapping("/consumer/dept/add")
  25. public boolean addDept(Dept dept) {
  26. return restTemplate.postForObject(REST_URL_PREFIX + (num.getAndIncrement() % 3 + 1) + "/dept/add/", dept, Boolean.class);
  27. }
  28. @RequestMapping("/consumer/dept/get/{id}")
  29. public Dept queryById(@PathVariable("id") Long id) {
  30. return restTemplate.getForObject(REST_URL_PREFIX + (num.getAndIncrement() % 3 + 1) + "/dept/get/" + id, Dept.class);
  31. }
  32. @RequestMapping("/consumer/dept/list")
  33. public List<Dept> queryAll() {
  34. return restTemplate.getForObject(REST_URL_PREFIX + (num.getAndIncrement() % 3 + 1) + "/dept/list", List.class);
  35. }
  36. }

启动测试刷新浏览器,得到如下即环境搭建成功

SpringCloud04:SpringCloud Rest学习环境搭建 - 图9

SpringCloud04:SpringCloud Rest学习环境搭建 - 图10

SpringCloud04:SpringCloud Rest学习环境搭建 - 图11