Rest microservice building case engineering module

General introduction

1. Next, our spring MVC + mybatis + MySQL elementary and advanced course takes the Dept Department module as a general case of microservice
Consumer consumer consumer (Client) calls the service provided by Provider provider (Server) through REST

2. Review of Maven's subcontract module architecture
A simple Maven module structure is as follows:
----App parent a parent project aggregates many child projects (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)

A Project with multiple Module submodules
MicroServiceCloud first brought 3 sub modules under the parent Project
1. Overall entity / interface / public configuration encapsulated by microservicecloud API
2.microservicecloud-provider-dept-8001 service provider of microservice landing
3. Use of microservicecloud-consumer-dept-80 microservice call client
Little knowledge:

Port 80 is open for HTTP(HyperText Transport Protocol)
This is the most frequently used protocol for surfing the Internet. It is mainly used for the world wide web (WWW) protocol for information transmission.
You can visit the website by adding ": 80" to the HTTP address (i.e. "website address"),
Because the default port number of web browsing service is 80, you only need to enter the web address instead of ": 80".

This version of spring cloud

Construction steps

A.microservicecloud (overall parent Project)

  1. Create a new parent project microservicecloud. Remember that packaging is pom mode

  2. It is mainly to define POM files and propose the jar packages that are common to subsequent sub modules, which are similar to an abstract parent class
  3. pom

Specify the corresponding java version and common jar packages (abstract classes like Java can only be inherited and cannot be instantiated)

<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>
    <!-- Make sure that every time you compile java 1.8This version -->
   <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 Automatic generation get set Method  -->
   <lombok.version>1.16.18</lombok.version>
  </properties>
 
  <!-- Parent project management mechanism -->
  <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 (common sub module Module)

  1. New microservicecloud API
    Right click microservicecloud (overall parent Project)

    Check whether the parent project is microservicecloud

    Note: jar package

    View the changes in the parent project file after completion: the package with the child template is attached and the pom file changes

    The following nodes are added automatically:

    2. modify pom
<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><!-- Only when the declaration is displayed in a subclass can it have a clear inheritance performance. No exception is the default version of the parent class, otherwise it will be defined by itself -->
   <groupId>com.atguigu.springcloud</groupId>
   <artifactId>microservicecloud</artifactId>
   <version>0.0.1-SNAPSHOT</version>
  </parent>
 
  <artifactId>microservicecloud-api</artifactId><!-- current Module What's my name -->
 
  <dependencies><!-- current Module What needs to be used jar Package, add according to your own requirements. If the parent class already contains it, you can not write the version number -->
  <!-- Above creation Maven Module Auto build complete -->
   <dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
   </dependency>
  </dependencies>
 
 
 
</project>


3. Create a new Department Entity and use it with lombok


 
package com.atguigu.springcloud.entities;
 
import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
 //To warn
@SuppressWarnings("serial")
//Empty Constructor 
@NoArgsConstructor
//set and get methods for each method
@Data
//Chain style access
@Accessors(chain=true)
//All parameter constructor
//@AllArgsConstructor	
//Note that lombok plug-ins need to be installed to use lombok eclipse
public class Dept implements Serializable {//Class table relation map must be serialized
  private Long  deptno;   //Primary key
  private String  dname;   //Department name
  private String  db_source;//From that database, because the microservice architecture can correspond to one database for one service, and the same information is stored in different databases. If it is db_source2, write db_source2 here 
public Dept(String dname) {
	super();
	this.dname = dname;
}
  public static void main(String[] args) {
	Dept dept =new Dept();
	//Chain writing
	dept.setDb_source("123").setDeptno(11L).getDb_source();
	
}
  
}
 
 


Regenerate jar package


c.microservicecloud-provider-dept-8001 (Department microservice provider Module)

  1. Create a new microservicecloud-provider-dept-8001 (or return to the parent project after the jar package is created to see the pom file changes as before)
  2. POM
 
<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><!-- Introduce self defined api General package, you can use Dept department 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>
   <!-- Alibaba's connection pool -->
   <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
   </dependency>
   <!-- Journal -->
   <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>
    <!-- No longer publish to Tomcat Now because Boot Built in jetty Tomcat Plug ins belong to embedded containers -->
   <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>
   <!-- It will take effect immediately after modification. Hot deployment hot deployment plug-ins will be released automatically and built automatically after modification -->
   <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

  2. In the src/main/resources directory of the project, create a new mybatis folder, and then create a new mybatis.cfg.xml file
<?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"/><!-- L2 cache on -->
  </settings>
 
</configuration>
  1. MySQL create department database script (insert data into the database)
    DTABASE(): insert the name of my library
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('Development Department',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('Ministry of Personnel',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('Finance Department',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('Marketing Department',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('Operation and maintenance department',DATABASE());
 
SELECT * FROM dept;
  1. DeptDao Department interface
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<Dept> findAll();
}
 


  1. Create a new mapper folder in src/main/resources/mybatis directory, and then create 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>
 


  1. DeptService Department Service Interface
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();
}
 


  1. DeptServiceImpl department service interface implementation class
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();
  }
 
}
 


  1. DeptServiceImpl department service interface implementation class
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();
  }
  
  
  
}
 


  1. Deptprovider8001 app main startup class
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);
  }
}
 


  1. test
    http://localhost:8001/dept/get/2
    http://localhost:8001/dept/list
  2. Final project presentation

D.microservicecloud-consumer-dept-80 (Department microservice consumer Module)

  1. New microservicecloud-consumer-dept-80 (jar package)
  2. POM
<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>Department micro service consumers</description>
 
  <dependencies>
   <dependency><!-- Self defined 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>
   <!-- Effective immediately after modification, hot deployment -->
   <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. Write ConfigBean under com.atguigu.springcloud.cfgbeans package (similar to the injection Bean written by applicationContext.xml in spring)
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();
    }
}


  1. Create a new dept controller under the package com.atguigu.springcloud.controller.consumer Department micro service consumer REST
    I. RestTemplate
    a. What is it?
    RestTemplate provides a variety of convenient ways to access remote Http services. It is a simple and convenient access to restful service template class. It is a client template tool set provided by Spring for accessing Rest services
    b. Official website and use
    Official website address:
    https://docs.spring.io/spring-framework/docs/4.3.7.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
    Use:
    Using restTemplate to access restful interface is very simple and crude. (url, requestMap, ResponseBean.class) these three parameters respectively represent
    The object type to which the REST request address, request parameter, and HTTP response transformation are converted.
    II. code
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
{	
	//Calling address
    private static final String REST_URL_PREFIX = "http://localhost:8001";
    
    
    //Interface call through RestTemplate
    //Using restTemplate to access restful interface is very simple and crude.
    //(url, requestMap, ResponseBean.class) these three parameters respectively represent 
    //The object type to which the REST request address, request parameter, and HTTP response transformation are converted.
    @Autowired
    private RestTemplate restTemplate;
    
    @RequestMapping(value="/consumer/dept/add")
    public boolean add(Dept dept)
    {	
    	//It's no longer xxxservice.xxx, because no REST call helps you encapsulate a layer
         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 main startup class
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);
  }
}
 

 


  1. test
    http://localhost/consumer/dept/get/2
    http://localhost/consumer/dept/list
    http://localhost/consumer/dept/add?dname=AI
Published 17 original articles, won praise and 70 visitors
Private letter follow

Keywords: Maven Spring Mybatis Apache

Added by bsteimel on Thu, 06 Feb 2020 15:53:27 +0200