SpringCloud学习笔记(三):Rest微服务构建案例工程模块

需要具备的知识

1 springmvc+mybatis+mysql
2 Consumer消费者(Client)通过REST调用Provider提供者(Server)提供的服务
3 Maven的分包分模块:project下带三个子模块,microservicecloud-api:封装的整体entity/接口/公共配置等,microservicecloud-provider-dept-8001:微服务落地的服务提供者,microservicecloud-consumer-dept-80:微服务调用的客户端使用

构建

MicroServiceCloud父工程(Project)下初次带着3个子模块(Module):
microservicecloud-api:封装的整体entity/接口/公共配置等
microservicecloud-provider-dept-8001:微服务落地的服务提供者
microservicecloud-consumer-dept-80:微服务调用的客户端使用
前缀需要相同,因为约定大于配置

pom.xml:
spring-cloud-dependencies----------Dalston.SR1
spring-cloud-dependencies----------1.5.9.RELEASE

新建父工程microservicecloud

eclipse---->new---->Maven Project -->名字:microservicecloud
SpringCloud学习笔记(三):Rest微服务构建案例工程模块_第1张图片
packaging必须是pom的
主要是定义POM文件,将后续各个子模块公用的jar包等统一提出来,类似一个抽象父类
pom.xml

< 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 > 

新建microservicecloud-api

在刚才父工程右键新建–>其他–>Maven Moudle -->名字:microservicecloud-api–>packaging jar
SpringCloud学习笔记(三):Rest微服务构建案例工程模块_第2张图片
建完之后发现在父工程的pom.xml中最后多了

<moudles>
	<moudle>microservicecloud-api</moudle>
</moudles>

修改子模块microservicecloud-api的api

< 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 > com.atguigu.springcloud </ groupId > 
    < artifactId > microservicecloud </ artifactId > 
    < version > 0.0.1-SNAPSHOT </ version > 
   </ parent > 


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


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

部门entity配合lombok使用

在 microservicecloud - api 这个moudle中新建packge com.xxx.entiy
在包下新建Dept.java
Dept.java

 
package  com.atguigu.springcloud.entities; 
  
import  java.io.Serializable; 
  
import  lombok.Data; 
import  lombok.NoArgsConstructor; 
import  lombok.experimental.Accessors; 
  
@SuppressWarnings ( "serial" ) //当在可序列化的类上缺少 serialVersionUID 定义时的警告,这里是压制警告的作用。
@NoArgsConstructor //空参构造函数
@Data //get set方法 
@Accessors (chain= true ) //链式风格访问,chain 若为true,则setter方法返回当前对象
public   class  Dept  implements  Serializable  //必须序列化
{ 
   private  Long   deptno ;    //主键 
   private  String   dname ;    //部门名称 
   private  String   db_source ; //来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库 
   
   public  Dept(String  dname ) 
  { 
    super (); 
    this . dname  =  dname ; 
  } 
} 

添加完上面lombok的注解,通过eclipse右边的outline可以进行查看定义的方法时候生成

mvn clean install后给其它模块引用,达到通用目的。
也即需要用到部门实体的话,不用每个工程都定义一份,直接引用本模块即可。
(mvn install 的作用是将生成的jar在本地仓库生成,其他的模块引用的时候不需要从远程仓库调用,直接从本地即可。)

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

约定>配置>编码
和新建microservicecloud-api一样的步骤,名字是microservicecloud-provider-dept-8001 。
请检查,父类的pom.xml中同样会自动增加一moudles
pom.xml



< 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 > com.atguigu.springcloud </ groupId > 
    < artifactId > microservicecloud </ artifactId > 
    < version > 0.0.1-SNAPSHOT </ version > 
   </ parent > 


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


   < dependencies > 
    < dependency > <!-- 引入自己定义的 api 通用包,可以使用 Dept 部门Entity --> 
      < groupId > com.atguigu.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 > 

在ser/main/resources中添加application.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                                   # 等待连接获取的最大超时时间 

工程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 > 

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; 
//DATABASE()插入当前数据库的名字

新建com.xxx.dao,新建DeptDao.java

package  com.atguigu.springcloud.dao; 


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


@Mapper     //mybatis的自动配置里会扫描springboot的有效包路径
//下的带有@Mapper注解的接口,然后根据里面的mybatis注解生成mapper代理类。 
//  Mapper定义的接口和xml文件(相当于实现类)是对应的
public   interface  DeptDao 
{ 
   public   boolean  addDept(Dept  dept ); 
   public  Dept findById(Long  id ); 
   public  List<Dept> findAll(); 
} 

工程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.atguigu.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 > 
 

新建com.xxx.service下新建DeptService
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<Dept> list(); 
} 

新建com.xxx.service.impl下新建DeptServiceImpl

package  com.atguigu.springcloud.service.impl; 


import  java.util.List; 


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


import  com.atguigu.springcloud.dao.DeptDao; 
import  com.atguigu.springcloud.entities.Dept; 
import  com.atguigu.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(); 
  } 


} 

新建com.xxx.controller包下的DeptController.java

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<Dept> list() 
  { 
    return   service .list(); 
  }    
}  

在com.xxx包下创建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 ); 
  } 
}

启动----->test: http://localhost:8001/dept/get/2
工程目录
SpringCloud学习笔记(三):Rest微服务构建案例工程模块_第3张图片

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

和新建microservicecloud-api一样的步骤,名字是microservicecloud-consumer-dept-80
请检查,父类的pom.xml中同样会自动增加一moudles
pom.xml

< 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 > com.atguigu.springcloud </ groupId > 
    < artifactId > microservicecloud </ artifactId > 
    < version > 0.0.1-SNAPSHOT </ version > 
   </ parent > 


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


   < dependencies > 
    < dependency > <!-- 自己定义的 api  --> 
      < groupId > com.atguigu.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 > 

application.yml

server: 
   port:  80 

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
 //这个注解相当于将spring中的aplication.xml替换到springboot中的实体类中了,
public   class  ConfigBean 
{ 
     @Bean 
     public  RestTemplate getRestTemplate() 
    { 
          return   new  RestTemplate(); 
    }
    //这里相当于原来的aplication.xml中的
   //  

//application.xml==configBean(@configuration)
} 

com.atguigu.springcloud.controller包下新建DeptController_Consumer部门微服务消费者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.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 ) 
    { 
    	//使用restTemplate访问restful接口非常的简单粗暴无脑。 
		//(url, requestMap, ResponseBean.class)这三个参数分别代表  
		//REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。

		//这里的意思是通过consumer去访问provider的api接口,参数是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 ); 
    }    
} 
 

什么是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响应转换被转换成的对象类型。

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

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

转载于:https://www.cnblogs.com/LeesinDong/p/10835449.html

你可能感兴趣的:(SpringCloud学习笔记(三):Rest微服务构建案例工程模块)