Modules: Commodity Module, Order Module, User Module
1. 1. Technology selection and preparation
maven: version 3.8.8
Database: MySQL 8.0.32
Persistence layer: springData, jpa
Other java environments: SpringCloud Alibaba technology stack
2. Module design
springcloud- alibaba parent project
shop – common public module [entity class]
shop – user user service [port number: 807x]
shop – product merchandise microservice [port: 808x]
shop – order order microservice [port: 809x]
The simple structure is as follows:
3. A brief introduction to the implementation of microservices
In the microservice architecture, the most common scenario is the mutual call between microservices. In the e-commerce system, it is common for users to place orders to cover up the calls between microservices. The customer wants to initiate a request to place an order with the order microservice. Before saving the order with all your heart, you need to call the product microservice to query product information
Active call: service consumer Passive call: service provider
Two. 1. Create a parent project (remember to check the version)
Corresponding maven dependencies
<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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <groupId>com.itheima</groupId> <artifactId>springcloud-alibaba</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version> <spring-cloud-alibaba.version>2.1.0.RELEASE</spring-cloud-alibaba.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <!-- Version Correspondence: --> <!-- 2.3 Create a basic module --> <!-- 1 Create shop-common module, add dependency in pom.xml --> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${spring-cloud-alibaba.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project>
Three. 1. Create a common basic module shop-common
Import the corresponding 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>springcloud-alibaba</artifactId> <groupId>com.itheima</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>shop-common</artifactId> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.32</version> </dependency> </dependencies> </project>
as the picture shows:
Create a new com.example.server.pojo package in shop-common
Create entity class user
package com.example.server.pojo; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity(name = "shop-user") @Data public class User { @Id @GeneratedValue(strategy = GenerationType. IDENTITY) private Integer uid;//primary key private String username;//username private String password;//password private String telephone;//Mobile phone number }
Create entity class Product
package com.example.server.pojo; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; //commodity @Entity(name = "shop_product") @Data public class Product { @Id // The meaning of the annotation is mainly to generate a uniquely identified primary key for an entity, @GeneratedValue(strategy = GenerationType. IDENTITY) private Integer pid;//primary key private String pname;//product name private Double pprice;//commodity price private Integer stock;//stock }
Create entity class Order
package com.example.server.pojo; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; //Order @Entity(name = "shop_order") @Data public class Order { @Id @GeneratedValue(strategy = GenerationType. IDENTITY) private Long oid;//order id private Integer uid;//user id private String username;//username private Integer pid;//commodity id private String pname;//product name private Double pprice;//Commodity unit price private Integer number;//Purchase quantity }
4. Build user microservice module shop-user
Step: 1 Create a module and import dependencies
Directory Structure:
2 Create SpringBoot main class
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ShopUserApplication { public static void main(String[] args) { SpringApplication.run(ShopUserApplication.class, args); } }
3 Add configuration file
4 Create the necessary interface and implementation class (controller service dao) Create a new shop-user module, and then perform the following operations 1 Create 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>springcloud-alibaba</artifactId> <groupId>com.itheima</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>shop-user</artifactId> <dependencies> <dependency> <groupId>com.itheima</groupId> <artifactId>shop-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> </project>
5. Create a configuration file application.yml
server: port: 8071 spring: application: name: service-product datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql:///shop?serverTimezone=UTC &useUnicode=true &characterEncoding=utf-8 &useSSL=true username: root password: root jpa: properties: hibernate: hbm2ddl: auto: update dialect: org.hibernate.dialect.MySQL5InnoDBDialect
5. Build the product microservice module shop-product
pom.xml file
<?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>springcloud-alibaba</artifactId> <groupId>com.itheima</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>shop-product</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.itheima</groupId> <artifactId>shop-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> </project>
Write the main class springboot execution class
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ShopProductApplication { public static void main(String[] args) { SpringApplication.run(ShopProductApplication.class, args); } }
Create a configuration file application.yml
server: port: 8081 spring: application: name: service-product datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql:///springcloud_shop?serverTimezone=UTC &useUnicode=true &characterEncoding=utf-8 &useSSL=true username: root password: 123456 jpa: properties: hibernate: hbm2ddl: auto: update dialect: org.hibernate.dialect.MySQL5InnoDBDialect
Create an interface in com.example.productDao
package com.example.dao; import com.example.server.pojo.Product; import org.springframework.data.jpa.repository.JpaRepository; public interface ProductDao extends JpaRepository<Product,Integer> { }
Create ProductService interface and implementation class
ProductService
package com.example.service; import com.example.server.pojo.Product; public interface ProductService { Product findByPid(Integer pid); }
ProductServiceimpl
package com.example.service.impl; import com.example.dao.ProductDao; import com.example.server.pojo.Product; import com.example.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ProductServiceImpl implements ProductService { @Autowired private ProductDao productDao; @Override public Product findByPid(Integer pid) { return productDao.findById(pid).get(); } }
Create Controller
package com.example.controller; import com.alibaba.fastjson.JSON; import com.example.server.pojo.Product; import com.example.service.ProductService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController @Slf4j public class ProductController { @Autowired private ProductService productService; @GetMapping("/product/{pid}") public Product product(@PathVariable("pid") Integer pid) { Product product = productService.findByPid(pid); log.info("Query to product:" + JSON.toJSONString(product)); return product; } }
Create a MySQL database:
create database springcloud_shop; use springcloud_shop; create table shop_product ( pid int , pname VARCHAR(10) not NULL, pprice VARCHAR(10) not null, stock VARCHAR(10) not null ); create table shop_user( uid int not null primary key, username VARCHAR(20) , password VARCHAR(20), telephone VARCHAR(11) ); delete from shop_user create table shop_user ( uid integer not null auto_increment, userpassword varchar(255), telephone varchar(255), username varchar(255), primary key (uid) ) engine=InnoDB INSERT INTO shop_product VALUE(1,'Xiaomi','1000','5000'); INSERT INTO shop_product VALUE(2,'Huawei','2000','5000'); INSERT INTO shop_product VALUE(3,'Apple','3000','5000'); INSERT INTO shop_product VALUE(4,'OPPO','4000','5000');
Access the service through a browser localhost:8081/product/1
6. Microservice building order module shop-order
Create a module called shop-order and add springboot dependencies
<?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>springcloud-alibaba</artifactId> <groupId>com.itheima</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>shop-order</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.itheima</groupId> <artifactId>shop-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> </project>
Create springboot execution class
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ShopOrderApplication { public static void main(String[] args) { SpringApplication.run(ShopOrderApplication.class, args); } }
at com.example.serve..dao
OrderDao interface
package com.example.server.dao; import com.example.server.pojo.Order; import org.springframework.data.jpa.repository.JpaRepository; public interface OrderDao extends JpaRepository<Order, Long> { }
com.example.serve package interface
Order Service
package com.example.server.service; import com.example.server.pojo.Order; public interface OrderService { void save(Order order); }
OrderServiceImpl
package com.example.server.service.impl; import com.example.server.dao.OrderDao; import com.example.server.pojo.Order; import com.example.server.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderDao orderDao; @Override public void save(Order order) { orderDao. save(order); } }
Create a RestTemplate to call commodity microservices through restTemplate
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } }
create controller
package com.example.server.controller; import com.alibaba.fastjson.JSON; import com.example.server.pojo.Order; import com.example.server.pojo.Product; import com.example.server.service.OrderService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @Slf4j public class OrderController { @Autowired private RestTemplate restTemplate; @Autowired private OrderService orderService; //ready to buy 1 item @GetMapping("/order/prod/{pid}") public Order order(@PathVariable("pid") Integer pid) { log.info(">>The customer places an order, at this time, call the product microservice to query product information"); //Call commodity microservices through restTemplate Product product = restTemplate.getForObject( "http://localhost:8081/product/" + pid, Product.class); log.info(">>product information, query result:" + JSON.toJSONString(product)); Order order = new Order(); order.setUid(1); order.setUsername("Test User"); order.setPid(product.getPid()); order.setPname(product.getPname()); order.setPprice(product.getPprice()); order. setNumber(1); orderService. save(order); return order; } }
Visit after starting the service: localhost:8091/order/prod/1
Such a simple microservice environment is set up