完整源码-仅供参考

https://github.com/ChannD/SpringCloudDemo

前言

现在可以正式上手代码,我会用SpringMVC,MyBatis,MySQL为主要技术,以Dept部门模块做一个微服务通用案例, Consumer(消费者) 通过REST调用Provider提供者(Server) 提供的服务.有了这个基础的服务,后面就可以加入SpringCloud的一项项技术
用Maven的分包分模块架

[简单说明下Maven模块结构,一般是这样的]

  • app-parent
    • pom.xml(pom)
    • app-util
      • pom.xml(jar)
    • app-dao
      • pom.xml(jar)
    • app-service
      • pom.xml(jar)
    • app-web
      • pom.xml(war)

理解 : 也就是一个Project带着多个Module子模块, 我会编写一个
MicroServiceCloud父工程(Project) 下初次带着3个子模块(Module)

  • microservicecloud-api (封装的整体entity/接口/公共配置等)
  • microservicecloud-provider-dept-8001 (微服务落地的服务提供者)
  • microservicecloud-consumer-dept-80 (微服务调用的客户端使用,显然用80端口)

image.png

本次SpringCloud使用版本, 使用IDE(intellij IDEA)

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-dependencies</artifactId>
	<version>Dalston.SR1</version>
	<type>pom</type>
	<scope>import</scope>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-dependencies</artifactId>
	<version>1.5.9.RELEASE</version>
	<type>pom</type>
	<scope>import</scope>
</dependency>

项目构建步骤

A . microservicecloud 整体父工程Project构建

  • 新建父工程microservicecloud,切记是Packageing是pom模式
  • [图示,选择Maven工程]
  • image.png
  • image.png
  • image.png
  • image.png
  • IDEA会询问是否自动导入包,Enable Auto-import比较方便
  • image.png
  • 是定义POM文件,将后续各个子模块公用的jar包等统一提出来,类似一个抽象父类
<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.atguigu.springcloud</groupId>
  <artifactId>microservicecloud</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
 
 
  <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>
   <log4j.version>1.2.17</log4j.version>
   <lombok.version>1.16.18</lombok.version>
  </properties>
 
<!-- 父类工程的一种管理机制 -->
  <dependencyManagement>
   <dependencies>
     <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-dependencies</artifactId>
       <version>Dalston.SR1</version>
       <type>pom</type>
       <scope>import</scope>
     </dependency>
     <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-dependencies</artifactId>
       <version>1.5.9.RELEASE</version>
       <type>pom</type>
       <scope>import</scope>
     </dependency>
     <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.0.4</version>
     </dependency>
     <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid</artifactId>
       <version>1.0.31</version>
     </dependency>
     <dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>
       <version>1.3.0</version>
     </dependency>
     <dependency>
       <groupId>ch.qos.logback</groupId>
       <artifactId>logback-core</artifactId>
       <version>1.2.3</version>
     </dependency>
     <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>${junit.version}</version>
       <scope>test</scope>
     </dependency>
     <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>${log4j.version}</version>
     </dependency>
   </dependencies>
  </dependencyManagement>
</project>

B . microservicecloud-api公共子模块Module

  1. 新建microservicecloud-api(创建完成后请回到父工程查看pom文件变化)
  • 直接在项目上右击,建立Module(依然选择Maven项目)
  • image.png
  • image.png
  • image.png
  • image.png
    [父Pom变化]
    <modules>
        <module>microservicecloud-api</module>
    </modules>
  1. 修改POM[代码如下]
<?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>microservicecloud</artifactId>
        <groupId>com.chann.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>microservicecloud-api</artifactId><!-- 当前Module我自己叫什么名字 -->

    <dependencies><!-- 当前Module需要用到的jar包,按自己需求添加,如果父类已经包含了,可以不用写版本号 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>
  1. 新建部门Entity且配合lombok使用,和数据库类表关系映射[代码]
package com.chann.springcloud.entities;

import java.io.Serializable;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@SuppressWarnings("serial")
@NoArgsConstructor
@Data
@Accessors(chain=true)
public class Dept implements Serializable //必须序列化
{
    private Long  deptno;   //主键
    private String  dname;   //部门名称
    private String  db_source;//来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库

    public Dept(String dname)
    {
        super();
        this.dname = dname;
    }
}

  1. mvn clean install后给其它模块引用,达到通用目的。也即需要用到部门实体的话,不用每个工程都定义一份,直接引用本模块即可。

C . 创建 microservicecloud-provider-dept-8001 部门微服务提供者Module

  1. 新建microservicecloud-provider-dept-8001(创建方式如之前的方式)
  2. 编辑POM [代码]
<?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>microservicecloud</artifactId>
        <groupId>com.chann.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>microservicecloud-provider-dept-8001</artifactId>

    <dependencies>
        <dependency><!-- 引入自己定义的api通用包,可以使用Dept部门Entity -->
            <groupId>com.chann.springcloud</groupId>
            <artifactId>microservicecloud-api</artifactId>
            <version>${project.version}</version>
        </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>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- 修改后立即生效,热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>


</project>
  1. YML配置文件(resource目录)
server:
  port: 8001

mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.chann.springcloud.entities    # 所有Entity别名类所在包
  mapper-locations:
    - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件

spring:
  application:
    name: microservicecloud-dept #这个名字记住很重要,很重要,很重要
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
    url: jdbc:mysql://localhost:3306/cloudDB01              # 数据库名称
    username: root
    password: root
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间
 
 

  1. 工程src/main/resources目录下新建mybatis文件夹后新建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="cacheEnabled" value="true"/><!-- 二级缓存开启 -->
  </settings>
 
</configuration>

  1. MySQL创建部门数据库脚本
DROP DATABASE IF EXISTS cloudDB01;
CREATE DATABASE cloudDB01 CHARACTER SET UTF8;
USE cloudDB01;
CREATE TABLE dept
(
  deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  dname VARCHAR(60),
  db_source   VARCHAR(60)
);
 
INSERT INTO dept(dname,db_source) VALUES('开发部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('人事部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('财务部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('市场部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('运维部',DATABASE());
 
SELECT * FROM dept;
 
 
 

  1. DeptDao部门接口
package com.chann.springcloud.dao;

import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.chann.springcloud.entities.Dept;

@Mapper
public interface DeptDao
{
    public boolean addDept(Dept dept);

    public Dept findById(Long id);

    public List<Dept> findAll();
}

  1. 工程src/main/resources/mybatis目录下新建mapper文件夹后再建DeptMapper.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.chann.springcloud.dao.DeptDao">

    <select id="findById" resultType="Dept" parameterType="Long">
        select deptno,dname,db_source from dept where deptno=#{deptno}; 
    </select>
    <select id="findAll" resultType="Dept">
        select deptno,dname,db_source from dept; 
     </select>
    <insert id="addDept" parameterType="Dept">
        INSERT INTO dept(dname,db_source) VALUES(#{dname},DATABASE());
    </insert>

</mapper>
 

  1. DeptService部门服务接口
package com.chann.springcloud.service;

import java.util.List;

import com.chann.springcloud.entities.Dept;

public interface DeptService {
    public boolean add(Dept dept);

    public Dept get(Long id);

    public List<Dept> list();
}

  1. DeptServiceImpl部门服务接口实现类
package com.chann.springcloud.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chann.springcloud.dao.DeptDao;
import com.chann.springcloud.entities.Dept;
import com.chann.springcloud.service.DeptService;

@Service
public class DeptServiceImpl implements DeptService
{
    @Autowired
    private DeptDao dao ;

    @Override
    public boolean add(Dept dept)
    {
        return dao.addDept(dept);
    }

    @Override
    public Dept get(Long id)
    {
        return dao.findById(id);
    }

    @Override
    public List<Dept> list()
    {
        return dao.findAll();
    }

}


  1. DeptController部门微服务提供者REST
package com.chann.springcloud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.chann.springcloud.entities.Dept;
import com.chann.springcloud.service.DeptService;

@RestController
public class DeptController
{
    @Autowired
    private DeptService service;

    @RequestMapping(value="/dept/add",method=RequestMethod.POST)
    public boolean add(@RequestBody Dept dept)
    {
        return service.add(dept);
    }

    @RequestMapping(value="/dept/get/{id}",method=RequestMethod.GET)
    public Dept get(@PathVariable("id") Long id)
    {
        return service.get(id);
    }

    @RequestMapping(value="/dept/list",method=RequestMethod.GET)
    public List<Dept> list()
    {
        return service.list();
    }



}


  1. DeptProvider8001_App主启动类
package com.chann.springcloud;

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

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

  1. 测试(也就是打开地址测试是否正常)
{
  "deptno": 2,
  "dname": "人事部",
  "db_source": "cloudDB01"
}
[
  {
    "deptno": 1,
    "dname": "开发部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 2,
    "dname": "人事部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 3,
    "dname": "财务部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 4,
    "dname": "市场部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 5,
    "dname": "运维部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 6,
    "dname": "bigDate2018",
    "db_source": "cloudDB01"
  }
]
  1. 最终工程展现[图示]
    image.png

D . 创建microservicecloud-consumer-dept-80 部门微服务消费者Module

  1. 新建microservicecloud-consumer-dept-80
  2. POM文件[代码]
<?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>microservicecloud</artifactId>
        <groupId>com.chann.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>microservicecloud-consumer-dept-80</artifactId>
    <description>部门微服务消费者</description>

    <dependencies>
        <dependency><!-- 自己定义的api -->
            <groupId>com.chann.springcloud</groupId>
            <artifactId>microservicecloud-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 修改后立即生效,热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>


</project>
  1. YML文件
server:
  port: 80
  1. com.chann.springcloud.cfgbeans包下ConfigBean的编写(类似spring里面的applicationContext.xml写入的注入Bean)
package com.chann.springcloud.cfgbeans;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration //boot配置类  替代applicationContext.xml
public class ConfigBean
{
    @Bean
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    }
}

  1. com.chann.springcloud.controller包下新建DeptController_Consumer部门微服务消费者REST,消费者只管吃蛋糕,不管如何制作蛋糕,所以这个里面是不应该有什么Service层,
    • RestTemplate是什么

      • 如果回忆一下应该大家都记得一个东西 JDBCTemplate, 玩Redis的时候应该也记得有个东西叫 RedisTemplate,所以这个RestTemplate也提供了这种便利模板.也就是说如果想发Rest请求就使用这个就可以了.
      • RestTemplate提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集
    • 官网地址

    • 使用 : 使用restTemplate访问restful接口非常的简单粗暴无脑。
      (url, requestMap, ResponseBean.class)这三个参数分别代表
      REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。

    • [代码]

package com.chann.springcloud.controller;

import java.util.List;

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 com.chann.springcloud.entities.Dept;

@RestController
public class DeptController_Consumer
{
    private static final String REST_URL_PREFIX = "http://localhost:8001";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value="/consumer/dept/add")
    public boolean add(Dept dept)
    {
        return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add", dept, Boolean.class);
    }

    @RequestMapping(value="/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id)
    {
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id, Dept.class);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/consumer/dept/list")
    public List<Dept> list()
    {
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list", List.class);
    }
}


  1. DeptConsumer80_App主启动类
package com.chann.springcloud;

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


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

  1. 测试
    • 地址:http://localhost/consumer/dept/get/2
{
  "deptno": 2,
  "dname": "人事部",
  "db_source": "cloudDB01"
}
  • 地址:http://localhost/consumer/dept/list
[
  {
    "deptno": 1,
    "dname": "开发部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 2,
    "dname": "人事部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 3,
    "dname": "财务部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 4,
    "dname": "市场部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 5,
    "dname": "运维部",
    "db_source": "cloudDB01"
  },
  {
    "deptno": 6,
    "dname": "bigDate2018",
    "db_source": "cloudDB01"
  }
]
  • 地址:http://localhost/consumer/dept/add?dname=jianglong
true

[写入数据库成功]
image.png

总结

系统现在有个了一个部门微服务的提供者和部门微服务的消费者,一个服务做一件事情, 并且从技术角度看独立处理,独立进程

Q.E.D.

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

脸朝大海, 春暖花开 ----江大脸