# 从浅入深 学习 SpringCloud 微服务架构(二)模拟微服务环境(1)

时间:2024-04-26 07:08:24

从浅入深 学习 SpringCloud 微服务架构(二)模拟微服务环境(1)

段子手168

1、打开 idea 创建父工程

创建 artifactId 名为 spring_cloud_demo 的 maven 工程。

--> idea --> File 
--> New --> Project 
--> Maven 
	Project SDK: ( 1.8(java version "1.8.0_131" ) 
--> Next 
--> Groupld : ( djh.it )
	Artifactld : ( spring_cloud_demo )
	Version : 1.0-SNAPSHOT
--> Name: ( spring_cloud_demo )
	Location: ( D:\java_test\Intesij_idea\spring_cloud_demo )	
--> Finish

2、在父工程 spring_cloud_demo 的 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>djh.it</groupId>
    <artifactId>spring_cloud_demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
	
	<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
	
	<repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>http://repo.spring.io/libs-release-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

<!-- D:\java_test\Intesij_idea\spring_cloud_demo\pom.xml -->

3、在父工程 spring_cloud_demo 下,创建子工程(子模块)

1)创建 子工程(子模块)

--> 右键 spring_cloud_demo 父工程
--> Modules 
--> Maven 
--> Groupld : ( djh.it )
	Artifactld : ( product_service )
	Version : 1.0-SNAPSHOT
--> Next 
--> Module name: ( product_service )
	Content root : ( D:\java_test\Intesij_idea\spring_cloud_demo\product_service )
	Module file location: ( D:\java_test\Intesij_idea\spring_cloud_demo\product_service )
--> Finish

4、在子工程 product_service 的 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>spring_cloud_demo</artifactId>
        <groupId>djh.it</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>product_service</artifactId>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

</project>

<!-- D:\java_test\Intesij_idea\spring_cloud_demo\pom.xml -->

5、准备数据库表

— 创建数据库:
create database shop;

— 使用数据库:
use shop;

— 创建数据表:

	CREATE TABLE `tb_product` (
	  `id` int NOT NULL AUTO_INCREMENT,
	  `product_name` varchar(40) DEFAULT NULL COMMENT '名称',
	  `status` int DEFAULT NULL COMMENT '状态',
	  `price` decimal(10,2) DEFAULT NULL COMMENT '单价',
	  `product_desc` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '描述',
	  `caption` varchar(255) DEFAULT NULL COMMENT '标题',
	  `inventory` int DEFAULT NULL COMMENT '库存',
	  PRIMARY KEY (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3

— 插入数据:
insert into tb_product(id,product_name,status,price,product_desc,caption,inventory)
values (1,‘iPhone 15 Pro\n’,1,‘7999.00\n’,'iPhone 15 Pro 6.7 英寸或 6.1 英寸, \n超视网膜 XDR 显示屏,ProMotion 自适应刷新率技术,\n 钛金属搭配亚光质感玻璃背板, 灵动岛功能, A17 Pro 芯片,\n配备 6 核图形处理器, Pro 级摄像头系统,主摄 4800 万像素 | 超广角 | 长焦, 10 倍, \n支持 USB 3, 视频播放最长可达 29 小时。\n ',‘iPhone 15 Pro 巅峰之作\n’,99);

6、创建 商品实体类 Product.java


/**
 *  D:\java_test\Intesij_idea\spring_cloud_demo\product_service\src\main\java\djh\it\product\domain\Product.java
 *
 *  2024-4-17 商品实体类 Product.java
 */
package djh.it.product.domain;

import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigDecimal;

@Data
@Entity
@Table(name="tb_product")  //对应数据库中的数据表
public class Product {

    @Id
    private Long id;
    private String productName;
    private Integer status;
    private BigDecimal price;
    private String productDesc;
    private String caption;
    private Integer inventory;
}

7、创建 dao 持久层接口 ProductDao.java


/**
 *  D:\java_test\Intesij_idea\spring_cloud_demo\product_service\src\main\java\djh\it\product\dao\ProductDao.java
 *
 *  2024-4-17  dao 持久层接口 ProductDao.java
 */
package djh.it.product.dao;

import djh.it.product.domain.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface ProductDao
        extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {

}

8、创建 service 服务层 接口 ProductService.java


/**
 *  D:\java_test\Intesij_idea\spring_cloud_demo\product_service\src\main\java\djh\it\product\service\ProductService.java
 *
 *  2024-4-17  service 服务层 接口 ProductService.java
 */
package djh.it.product.service;

import djh.it.product.domain.Product;

public interface ProductService {
    //根据id查询
    Product findById(Long id);
    //保存
    void save(Product product);
    //更新
    void update(Product product);
    //删除
    void delete(Long id);
}

9、创建 service 服务层 实现类 ProductServiceImpl.java


/**
 *  D:\java_test\Intesij_idea\spring_cloud_demo\product_service\src\main\java\djh\it\product\service\Impl\ProductServiceImpl.java
 *
 *  2024-4-17  service 服务层 实现类
 */
package djh.it.product.service.Impl;

import djh.it.product.domain.Product;
import djh.it.product.dao.ProductDao;
import djh.it.product.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 findById(Long id) {
        return productDao.findById(id).get();
    }

    @Override
    public void save(Product product) {
        productDao.save(product);
    }

    @Override
    public void update(Product product) {
        productDao.save(product);
    }

    @Override
    public void delete(Long id) {
        productDao.deleteById(id);
    }
}

10、创建 商品的 controller 类 ProductController.java


/**
 *  D:\java_test\Intesij_idea\spring_cloud_demo\product_service\src\main\java\djh\it\product\controller\ProductController.java
 *
 *  2024-4-17 商品的 controller 类 ProductController.java
 */
package djh.it.product.controller;

import djh.it.product.domain.Product;
import djh.it.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        Product product = productService.findById(id);
        return product;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public String save (@RequestBody Product product){
        productService.save(product);
        return "保存成功";
    }

}

11、创建配置文件 application.yml


## D:\java_test\Intesij_idea\spring_cloud_demo\product_service\src\main\resources\application.yml

server:
  port: 9001  # 启动端口 命令行注入。
#  port: ${port:56010}  # 启动端口设置为动态传参,如果未传参数,默认端口为 56010
#  servlet:
#    context-path: /application1

spring:
  application:
    name: service-product  #spring应用名, # 注意 FeignClient 不支持名字带下划线
#  main:
#    allow-bean-definition-overriding: true # SpringBoot2.1 需要设定。
  datasource:
    driver-class-name: com.mysql.jdbc.Driver  # mysql 驱动
#    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8
    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 12311
  jpa:
    database: MySQL
    show-sql: true
    open-in-view: true


12、创建 启动类 ProductApplication.java


/**
 *   D:\java_test\Intesij_idea\spring_cloud_demo\product_service\src\main\java\djh\it\product\ProductApplication.java
 *
 *   2024-4-17  启动类 ProductApplication.java
 */
package djh.it.product;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;

@SpringBootApplication
@EntityScan("djh.it.product.domain")
public class ProductApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProductApplication.class, args);
    }
}

13、运行启动类,进行测试

浏览器地址栏输入:http://127.0.0.1:9001/product/1

输出 mysql 数据库的第一条记录:

在这里插入图片描述

在这里插入图片描述

上一节文章查看请点击
# 从浅入深 学习 SpringCloud 微服务架构(一)基础知识