SpringCloud02:Rest微服务构建案例工程模块

本系列对应的是尚硅谷周阳Spring Cloud的思维导图整理的笔记,用来方便自己后面的知识点回顾。分别以每个知识点作为一篇文章详细讲述。

知识点传送门:
项目源码

  • SpringCloud01:微服务概述与SpringCloud
  • SpringCloud02:Rest微服务构建案例工程模块
  • SpringCloud03:Eureka服务注册与发现
  • SpringCloud04:Ribbon负载均衡
  • SpringCloud05:Feign负载均衡
  • SpringCloud06:Hystrix断路器
  • SpringCloud07:zuul路由网关
  • SpringCloud08:SpringCloud Config分布式配置中心

一、总体介绍

这里以Dept部门模块做一个微服务通用案例Consumer消费者(Client)通过REST调用Provider提供者(Server)提供的服务

1.Maven的分包分模块架构复习

一个简单的Maven模块结构是这样的:
---- app-parent 一个父项目(app-parent)聚合很多子项目(app-util,app-dao,app-service,app-web)
|---- 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 微服务调用的客户端使用

二、构建步骤

1.microservicecloud整体父工程Project

1)新建父工程microservicecloud,切记是Packageing是pom模式
2)主要是定义POM文件,将后续各个子模块公用的jar包等统一提出来,类似一个抽象父类
3)POM文件


  4.0.0

  com.atguigu.springcloud
  microservicecloud
  0.0.1-SNAPSHOT
  pom

  
   UTF-8
   1.8
   1.8
   4.12
   1.2.17
   1.16.18
  

  
   
     
       org.springframework.cloud
       spring-cloud-dependencies
       Dalston.SR1
       pom
       import
     
     
       org.springframework.boot
       spring-boot-dependencies
       1.5.9.RELEASE
       pom
       import
     
     
       mysql
       mysql-connector-java
       5.0.4
     
     
       com.alibaba
       druid
       1.0.31
     
     
       org.mybatis.spring.boot
       mybatis-spring-boot-starter
       1.3.0
     
     
       ch.qos.logback
       logback-core
       1.2.3
     
     
       junit
       junit
       ${junit.version}
       test
     
     
       log4j
       log4j
       ${log4j.version}
     
   
  

2.microservicecloud-api公共子模块Module

1)新建microservicecloud-api
创建完成后请回到父工程查看pom文件变化
2)修改POM文件


  4.0.0

  
   com.atguigu.springcloud
   microservicecloud
   0.0.1-SNAPSHOT
  

  microservicecloud-api

  
   
     org.projectlombok
     lombok
   
  


3)新建部门Entity且配合lombok使用

 
package com.atguigu.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;
  }
}

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

3.microservicecloud-provider-dept-8001 部门微服务提供者Module

1)新建microservicecloud-provider-dept-8001
创建完成后请回到父工程查看pom文件变化
2)修改POM文件




  4.0.0

  
   com.atguigu.springcloud
   microservicecloud
   0.0.1-SNAPSHOT
  

  microservicecloud-provider-dept-8001

  
   
     com.atguigu.springcloud
     microservicecloud-api
     ${project.version}
   
   
     junit
     junit
   
   
     mysql
     mysql-connector-java
   
   
     com.alibaba
     druid
   
   
     ch.qos.logback
     logback-core
   
   
     org.mybatis.spring.boot
     mybatis-spring-boot-starter
   
   
     org.springframework.boot
     spring-boot-starter-jetty
   
   
     org.springframework.boot
     spring-boot-starter-web
   
   
     org.springframework.boot
     spring-boot-starter-test
   
   
   
     org.springframework
     springloaded
   
   
     org.springframework.boot
     spring-boot-devtools
   
  


3)创建YML文件

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

4)工程src/main/resources目录下新建mybatis文件夹后新建mybatis.cfg.xml文件



  

  
   
  

5)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;

6)DeptDao部门接口

package com.atguigu.springcloud.dao;

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

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

  public Dept findById(Long id);

  public List findAll();
}

7)工程src/main/resources/mybatis目录下新建mapper文件夹后再建DeptMapper.xml



 

 
  
  
  
   INSERT INTO dept(dname,db_source) VALUES(#{dname},DATABASE());
  
  

8)DeptService部门服务接口

package com.atguigu.springcloud.service;

import java.util.List;

import com.atguigu.springcloud.entities.Dept;

public interface DeptService
{
  public boolean add(Dept dept);
  public Dept    get(Long id);
  public List list();
}

9)DeptController部门微服务提供者REST

package com.atguigu.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.atguigu.springcloud.entities.Dept;
import com.atguigu.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 list()
  {
   return service.list();
  } 
}

10)DeptProvider8001_App主启动类DeptProvider8001_App

package com.atguigu.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);
  }
}

11)测试
浏览器输入:

  • http://localhost:8001/dept/get/2
  • http://localhost:8001/dept/list

4.microservicecloud-consumer-dept-80部门微服务消费者Module

1)新建microservicecloud-consumer-dept-80
2)修改POM


  4.0.0

  
   com.atguigu.springcloud
   microservicecloud
   0.0.1-SNAPSHOT
  

  microservicecloud-consumer-dept-80
  部门微服务消费者

  
   
     com.atguigu.springcloud
     microservicecloud-api
     ${project.version}
    
   
     org.springframework.boot
     spring-boot-starter-web
   
   
   
     org.springframework
     springloaded
   
   
     org.springframework.boot
     spring-boot-devtools
      
  

3)新建YML文件

server:
  port: 80

4)com.atguigu.springcloud.cfgbeans包下ConfigBean的编写(类似spring里面的applicationContext.xml写入的注入Bean)

package com.atguigu.springcloud.cfgbeans;
 
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();
    }
}

5)com.atguigu.springcloud.controller包下新建DeptController_Consumer部门微服务消费者REST

RestTemplate是什么:
RestTemplate提供了多种便捷访问远程Http服务的方法,
是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集
官网地址
https://docs.spring.io/spring-framework/docs/4.3.7.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
使用
使用restTemplate访问restful接口非常的简单粗暴无脑。
(url, requestMap, ResponseBean.class)这三个参数分别代表
REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。

package com.atguigu.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.atguigu.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 list()
    {
         return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list", List.class);
    }   
}

6)DeptConsumer80_App主启动类

package com.atguigu.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);
  }
}

7)测试

  • http://localhost/consumer/dept/get/2
  • http://localhost/consumer/dept/list
  • http://localhost/consumer/dept/add?dname=AI

你可能感兴趣的:(SpringCloud02:Rest微服务构建案例工程模块)