以 商品管理模块 做一个微服务架构通用案例,消费者Consumer(Client)通过REST调用 提供者 Provider(Server)提供的商品管理服务。
一、创建父工程微服务microservice-cloud-01
1、pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mengxuegu.springcloud</groupId> <artifactId>microservice-cloud-01</artifactId> <version>1.0-SNAPSHOT</version> <modules> <module>../microservice-cloud-02-api</module> <module>../microservice-cloud-03-provider-product-8001</module> <module>../microservice-cloud-04-consumer-product-80</module> </modules> <!-- 手动指定 pom --> <packaging>pom</packaging> <!-- spring boot 采用 2.0.7 版本 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.7.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <!-- spring cloud 采用 Finchley.SR2 版本 --> <spring-cloud.version>Finchley.SR2</spring-cloud.version> </properties> <!--依赖声明--> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <!--maven不支持多继承,使用import来依赖管理配置--> <scope>import</scope> </dependency> <!--导入 mybatis 启动器--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--druid数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> </dependencyManagement> </project>
二、创建子工程微服务microservice-cloud-02-api
1、实体
package com.mengxuegu.springcloud.entities; import java.io.Serializable; public class Product implements Serializable { //主键 private Long pid; //产品名称 private String productName; // 来自哪个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库 private String dbSource; public Product() { } public Product(String productName) { this.productName = productName; } public Product(Long pid, String productName, String dbSource) { this.pid = pid; this.productName = productName; this.dbSource = dbSource; } public Long getPid() { return pid; } public void setPid(Long pid) { this.pid = pid; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getDbSource() { return dbSource; } public void setDbSource(String dbSource) { this.dbSource = dbSource; } }
2、pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>microservice-cloud-01</artifactId> <groupId>com.mengxuegu.springcloud</groupId> <version>1.0-SNAPSHOT</version> <relativePath>../microservice-cloud-01/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microservice-cloud-02-api</artifactId> </project>
三、创建子微服务microservice-cloud-03-provider-product-8001
1、controller
package com.mengxuegu.springcloud.controller; import com.mengxuegu.springcloud.entities.Product; import com.mengxuegu.springcloud.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class ProductController { @Autowired private ProductService productService; @RequestMapping(value = "/product/add", method = RequestMethod.POST) public boolean add(@RequestBody Product product) { return productService.add(product); } @RequestMapping(value = "/product/get/{id}", method = RequestMethod.GET) public Product get(@PathVariable("id") Long id) { return productService.get(id); } @RequestMapping(value = "/product/list", method = RequestMethod.GET) public List<Product> list() { return productService.list(); } }
2、service
package com.mengxuegu.springcloud.service; import com.mengxuegu.springcloud.entities.Product; import java.util.List; public interface ProductService { boolean add(Product product); Product get(Long id); List<Product> list(); }
3、serviceImpl
package com.mengxuegu.springcloud.service.impl; import com.mengxuegu.springcloud.entities.Product; import com.mengxuegu.springcloud.mapper.ProductMapper; import com.mengxuegu.springcloud.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service //一定不要少了 public class ProductServiceImpl implements ProductService { @Autowired ProductMapper productMapper; @Override public boolean add(Product product) { return productMapper.addProduct(product); } @Override public Product get(Long id) { return productMapper.findById(id); } @Override public List<Product> list() { return productMapper.findAll(); } }
4、启动类
package com.mengxuegu.springcloud; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan("com.mengxuegu.springcloud.mapper") @SpringBootApplication public class ProductProvider_8001 { public static void main(String[] args) { SpringApplication.run(ProductProvider_8001.class, args); } }
5、mapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mengxuegu.springcloud.mapper.ProductMapper"> <select id="findById" resultType="Product" parameterType="Long"> select pid, product_name, db_source from product where pid=#{pid}; </select> <select id="findAll" resultType="Product"> select pid, product_name, db_source from product; </select> <insert id="addProduct" parameterType="Product"> INSERT INTO product(product_name, db_source) VALUES(#{productName}, DATABASE()); </insert> </mapper>
6、mybatis.cfg.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!--开启驼峰命名--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
7、application.yml
server: port: 8001 mybatis: config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径 type-aliases-package: com.mengxuegu.springcloud.entities # 所有Entity别名类所在包 mapper-locations: classpath:mybatis/mapper/**/*.xml # mapper映射文件 spring: application: name: microservice-product #这个很重要,这在以后的服务与服务之间相互调用一般都是根据这个name datasource: type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型 driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动包 url: jdbc:mysql://127.0.0.1:3306/springcloud_db01?serverTimezone=GMT%2B8 # 数据库名称 username: root password: root dbcp2: min-idle: 5 # 数据库连接池的最小维持连接数 initial-size: 5 # 初始化连接数 max-total: 5 # 最大连接数 max-wait-millis: 150 # 等待连接获取的最大超时时间
8、pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>microservice-cloud-01</artifactId> <groupId>com.mengxuegu.springcloud</groupId> <version>1.0-SNAPSHOT</version> <relativePath>../microservice-cloud-01/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microservice-cloud-03-provider-product-8001</artifactId> <dependencies> <dependency> <groupId>com.mengxuegu.springcloud</groupId> <artifactId>microservice-cloud-02-api</artifactId> <version>${project.version}</version> </dependency> <!--springboot web启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mybatis 启动器--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> </dependencies> </project>
四、子微服务microservice-cloud-04-consumer-product-80
1、配置类
package com.mengxuegu.springcloud.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration //标识配置类 public class ConfigBean { @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } }
2、controller
package com.mengxuegu.springcloud.controller; import com.mengxuegu.springcloud.entities.Product; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.List; @RestController public class ProductController_Consumer { private static final String REST_URL_PREFIX = "http://localhost:8001"; @Autowired private RestTemplate restTemplate; @RequestMapping(value = "/consumer/product/add") public boolean add(Product product) { return restTemplate.postForObject(REST_URL_PREFIX + "/product/add", product, Boolean.class); } @RequestMapping(value = "/consumer/product/get/{id}") public Product get(@PathVariable("id") Long id) { return restTemplate.getForObject(REST_URL_PREFIX + "/product/get/" + id, Product.class); } @RequestMapping(value = "/consumer/product/list") public List<Product> list() { return restTemplate.getForObject(REST_URL_PREFIX + "/product/list", List.class); } }
3、启动类
package com.mengxuegu.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProductConsumer_80 { public static void main(String[] args) { SpringApplication.run(ProductConsumer_80.class, args); } }
4、application.yml
server: port: 80
5、pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>microservice-cloud-01</artifactId> <groupId>com.mengxuegu.springcloud</groupId> <version>1.0-SNAPSHOT</version> <relativePath>../microservice-cloud-01/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microservice-cloud-04-consumer-product-80</artifactId> <dependencies> <dependency> <groupId>com.mengxuegu.springcloud</groupId> <artifactId>microservice-cloud-02-api</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
五、测试截图
1、启动微服务microservice-cloud-03-provider-product-8001
2、启动微服务microservice-cloud-04-consumer-product-80
六、数据库脚本
DROP DATABASE IF EXISTS springcloud_db01;
CREATE DATABASE springcloud_db01 CHARACTER SET UTF8;
USE springcloud_db01;
CREATE TABLE product
(
pid BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(50),
db_source VARCHAR(50)
);
INSERT INTO product(product_name,db_source) VALUES('格力空调',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('海尔冰箱',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('小短裙',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('羽绒服',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('韩版休闲鞋',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('高贵鞋',DATABASE());
SELECT * FROM product;
DROP DATABASE IF EXISTS springcloud_db02;
CREATE DATABASE springcloud_db02 CHARACTER SET UTF8;
USE springcloud_db02;
CREATE TABLE product
(
pid BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(50),
db_source VARCHAR(50)
);
INSERT INTO product(product_name,db_source) VALUES('格力空调',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('海尔冰箱',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('小短裙',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('羽绒服',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('韩版休闲鞋',DATABASE());
INSERT INTO product(product_name,db_source) VALUES('高贵鞋',DATABASE());
SELECT * FROM product;