Rest构建分布式 SpringCloud微服务架构项目

一、开发环境:jdk  1.8、Maven  3.x、IDEA  2019.1.4、SpringBoot   2.0.7、spring Cloud  最新的稳定版  Finchley SR2   搭配SpringBoot   2.0.7稳定版(https://spring.io/projects/spring-cloud、GA   greneral Availability   正式发布版 、PRE  预览版  内部测试版 、SNAPSHOT 快照版  稳定 但是人在持续更新)

二、修改Maven配置文件

   <mirror>
        <id>alimaven</id>
        <mirrorOf>central</mirrorOf>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
   </mirror> 
<profile> <id>jdk-1.8</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> </profile>

三、微服务架构项目需求

  1、以商品管理模块 做一个微服务架构通用案例  消费者ConsumerClient)   通过REST调用  提供者 Provider(Server)   提供商品的管理服务

  2、Maven的分包 分模块架构(一个Project父工程下有多个Module子模块)

    a:microservice-cloud-01父工程(Project) 下面有3个子工程

    b:microservice-cloud-02-api 封装整体Entity/接口/公共配置

    c:microservice-cloud-03-provider-product-8001 微服务的服务提供者Provider

    d:microservice-cloud-04-consumer-product-80 微服务的消费者 Consumer

  浏览器发送URL请求服务默认端口都是80  只需要输入IP或者域名即可可以省略80

四、Project父工程  microservice-cloud-01删除工程里的src

pom.xml文件中 添加 <packaging>pom</packaging>手动指定pom

<!--springboot  采用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>

五、构建公共模块  microservice-cloud-02-api

创建实体类

package cn.zrf.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;
    }
}

六、构建服务提供者  microservice-cloud-03-provider-product-8001

1、配置pom配置文件;并跟microservice-cloud-02-api产生关系

<dependencies>
        <dependency>
            <groupId>cn.zrf</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>
            <version>8.0.13</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
    </dependencies>

2、配置application.yml 文件

server:
  port: 8001
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: cn.zrf.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: 169695
    dbcp2:
      min-idle: 5                                # 数据库连接池的最小维持连接数
      initial-size: 5                            # 初始化连接数
      max-total: 5                               # 最大连接数
      max-wait-millis: 150                       # 等待连接获取的最大超时时间

3、创建mapper接口

package cn.zrf.springcloud.mapper;

import cn.zrf.springcloud.entities.Product;

import java.util.List;

public interface ProductMapper {
    Product findById(Long pid);
    List<Product> findAll();
    boolean addProduct(Product product);
}

4、Mybatis  相关的配置 创建mybatis文件夹配置mybatis.cfg.xml文件   文件路径  在mybatis文件夹下建立mappe文件夹写mapper映射文件

  4.1、配置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"></setting>
    </settings>
</configuration>

  4.2、配置mapper映射文件

<?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="cn.zrf.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(#{productNmae},#{dbSource})
    </insert>
</mapper>

5、创建服务层service

package cn.zrf.springcloud.service;

import cn.zrf.springcloud.entities.Product;

import java.util.List;

public interface ProductService {
    Product findById(Long pid);
    List<Product> findAll();
    boolean addProduct(Product product);
}


实现类:
package cn.zrf.springcloud.service.impl;

import cn.zrf.springcloud.entities.Product;
import cn.zrf.springcloud.mapper.ProductMapper;
import cn.zrf.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 Product findById(Long pid) {
        return productMapper.findById(pid);
    }

    @Override
    public List<Product> findAll() {
        return productMapper.findAll();
    }

    @Override
    public boolean addProduct(Product product) {
        return productMapper.addProduct(product);
    }
}

6、创建控制层Controoler  提供者

package cn.zrf.springcloud.controller;

import cn.zrf.springcloud.entities.Product;
import cn.zrf.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.addProduct(product);
    }
    @RequestMapping(value = "/product/get/{id}",method = RequestMethod.GET)
    public Product get(@PathVariable("id")Long id){
        return productService.findById(id);
    }
    @RequestMapping(value = "/product/get/list",method = RequestMethod.GET)
    public List<Product> getAll(){
        return productService.findAll();
    }
}

 7、创建主启动类

package cn.zrf.springcloud;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("cn.zrf.springcloud.mapper")
@SpringBootApplication
public class ProductProvider_8001 {
    public static void main(String[] args) {
        SpringApplication.run(ProductProvider_8001.class,args);
    }
}

 

七、构建消费者   microservice-cloud-04-consumer-product-80

1、pom.xml配置 跟microservice-cloud-02-api产生关系

<dependencies>
        <dependency>
            <groupId>cn.zrf</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>

    </dependencies>

2、配置appicztion.yml 文件

server:
  port: 80

 3、自定义Rest相关配置类

 @Configuration
public class ConfigBean {
    // 向容器中添加RestTemplate 组件   直接该组件调用EREST接口
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

 4、创建控制层 -消费者

@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(@RequestBody 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/get/list")
    public List<Product> list() {
        return restTemplate.getForObject(REST_URL_PREFIX + "/product/get/list" , List.class);
    }

}

 5、创建启动类

@SpringBootApplication
public class ProductConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(ProductConsumer_80.class,args);
    }
}

 

posted @ 2019-08-27 15:39  怕黑,可是却恋上了夜  阅读(408)  评论(0编辑  收藏  举报