java框架之SpringCloud(2)-Rest微服務案例

上一章節已經對微服務與 SpringCloud 作了介紹,爲方便後面學習,下面以 Dept 部門模塊爲例作一個微服務通用 Demo —— Consumer 消費者(Client) 經過 REST 調用 Provider 提供者(Server)提供的服務,後續學習在該 Demo 基礎上集成新功能。html

環境

IDE:IDEAjava

SpringBoot 版本:1.5.20.RELEASEmysql

SpringCloud 版本:Dalston.RELEASEweb

構建工具:Mavenspring

開工

父工程構建

新建工程,打包方式爲 pom ,工程名爲 "microservicecloud" 依賴以下:sql

<?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">
  <modelVersion>4.0.0</modelVersion>

  <groupId>zze.springcloud</groupId>
  <artifactId>microservicecloud</artifactId>
  <version>1.0-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>
      <!--Spring Cloud-->
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Dalston.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!--Spring Boot-->
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>1.5.20.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!--Mysql Connector-->
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
      </dependency>
      <!--DataSource-->
      <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>
      <!--log-->
      <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.2.3</version>
      </dependency>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
      </dependency>
      <!--test-->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>
pom.xml

下面新建的子工程的父工程都爲 microservicecloud ,打包方式都爲 jar。數據庫

公共子模塊

新建名爲 "microservicecloud-api" 的子工程,依賴以下:apache

<?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>zze.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../microservicecloud/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <description>封裝總體的 entity 、接口、公共配置等</description>

    <artifactId>microservicecloud-api</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>
pom.xml

新建部門 Entity:api

package zze.springcloud.entities;

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

import java.io.Serializable;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Accessors(chain = true)
public class Dept implements Serializable {
    private Long deptNo; // 主鍵
    private String deptName; // 部門名稱
    private String dbSource; // 來自哪一個數據庫,由於微服務架構中一個服務能夠對應一個數據庫,信息可被存儲到不一樣數據庫
}
zze.springcloud.entities.Dept

微服務Provider

新建名爲 "microservicecloud-provider-dept-8001" 的子工程做爲微服務提供者,依賴以下:緩存

<?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>zze.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../microservicecloud/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <description>部門微服務提供者</description>
    <artifactId>microservicecloud-provider-dept-8001</artifactId>

    <dependencies>
        <dependency>
            <groupId>zze.springcloud</groupId> <!--引入自定義的 api 通用包,能夠使用 Dept 部門 Entity-->
            <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>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>
pom.xml

初始化數據庫表結構及數據:

DROP DATABASE IF EXISTS springcloud_8001;
CREATE DATABASE springcloud_8001 CHARACTER SET UTF8;
USE springcloud_8001;

CREATE TABLE dept
(
  dept_no   BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  dept_name VARCHAR(60),
  db_source VARCHAR(60)
);

INSERT INTO dept(dept_name, db_source)
VALUES ('開發部', DATABASE());
INSERT INTO dept(dept_name, db_source)
VALUES ('人事部', DATABASE());
INSERT INTO dept(dept_name, db_source)
VALUES ('財務部', DATABASE());
INSERT INTO dept(dept_name, db_source)
VALUES ('市場部', DATABASE());
INSERT INTO dept(dept_name, db_source)
VALUES ('運維部', DATABASE());

SELECT * FROM dept;
dept.sql

配置數據源及 mybatis 相關,指定服務端口爲 8001:

server:
  port: 8001

mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml # mybatis 配置文件路徑
  type-aliases-package: zze.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:///springcloud_8001 # 數據庫鏈接 root
    username: root
    password: root
    dbcp2:
      min-idle: 5 # 數據庫鏈接池的最小維持鏈接數
      initial-size: 5 # 初始化鏈接數
      max-total: 5 # 最大鏈接數
      max-wait-millis: 200 # 等待鏈接獲取的最大超時時間
application.yml
<?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"/> <!--二級緩存開啓-->
        <!--啓用駝峯命名,表字段 user_name 可映射到 userName -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
mybatis/mybatis.cfg.xml

編寫部門 Dao:

package zze.springcloud.dao;

import org.apache.ibatis.annotations.Mapper;
import zze.springcloud.entities.Dept;

import java.util.List;

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

    public Dept findById(Long id);

    public List<Dept> findAll();
}
zze.springcloud.dao.DeptDao
<?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="zze.springcloud.dao.DeptDao">
    <select id="findById" resultType="Dept" parameterType="Long">
        select dept_no,dept_name,db_source from dept where dept_no=#{deptNo};
    </select>

    <select id="findAll" resultType="Dept">
        select dept_no,dept_name,db_source from dept;
    </select>

    <select id="addDept" parameterType="Dept">
        insert into dept(dept_name,db_source) values(#{deptName},DATABASE());
    </select>
</mapper>
mybatis/mapper/DeptMapper.xml

編寫部門 Service:

package zze.springcloud.service;

import zze.springcloud.entities.Dept;

import java.util.List;

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

    public Dept get(Long id);

    public List<Dept> list();
}
zze.springcloud.service.DeptService
package zze.springcloud.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zze.springcloud.dao.DeptDao;
import zze.springcloud.entities.Dept;
import zze.springcloud.service.DeptService;

import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptDao deptDao;

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

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

    @Override
    public List<Dept> list() {
        return deptDao.findAll();
    }
}
zze.springcloud.service.impl.DeptServiceImpl

編寫部門 Controller:

package zze.springcloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import zze.springcloud.entities.Dept;
import zze.springcloud.service.DeptService;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @PostMapping("/add")
    public boolean add(@RequestBody Dept dept) {
        return deptService.add(dept);
    }

    @GetMapping("/get/{id}")
    public Dept get(@PathVariable Long id) {
        return deptService.get(id);
    }

    @GetMapping("/list")
    public List<Dept> list() {
        return deptService.list();
    }
}
zze.springcloud.controller.DeptController

編寫主啓動類:

package zze.springcloud;

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

@SpringBootApplication
public class Application_8001 {

    public static void main(String[] args) {
        SpringApplication.run(Application_8001.class, args);
    }
}
zze.springcloud.Application_8001

測試:

運行主啓動類,訪問 http://localhost:8001/dept/list:

test

微服務Consumer

新建名爲 "microservicecloud-consumer-dept-80" 的子工程做爲微服務提供者,依賴以下:

<?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>zze.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../microservicecloud/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <description>部門微服務消費者</description>

    <artifactId>microservicecloud-consumer-dept-80</artifactId>

    <dependencies>
        <dependency>
            <groupId>zze.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>
pom.xml

指定服務端口爲 80:

server:
  port: 80
application.yml

新建配置類,註冊 RestTemplate bean:

package zze.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 restTemplate() {
        return new RestTemplate();
    }
}
zze.springcloud.cfgbeans.ConfigBean

新建 Controller,經過 RestTemplate bean 使用 Provider 提供的服務:

package zze.springcloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import zze.springcloud.entities.Dept;

import java.util.List;

@RestController
@RequestMapping("/consumer/dept")
public class DeptController {
    // 微服務 Provider 的服務地址
    private final static String REST_URL_PREFIX = "http://127.0.0.1:8001";

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/add")
    public boolean add(@RequestBody Dept dept) {
        return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept,Boolean.class);
    }

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

    @GetMapping("/list")
    public List<Dept> list(){
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
    }
}
zze.springcloud.controller.DeptController

編寫主啓動類:

package zze.springcloud;

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

@SpringBootApplication
public class Application_80 {

    public static void main(String[] args) {
        SpringApplication.run(Application_80.class, args);
    }
}
zze.springcloud.Application_80

測試:

一、先啓動部門微服務提供者即 microservicecloud-provider-dept-8001 工程。
二、再啓動部門微服務消費者即 microservicecloud-consumer-dept-80 工程,訪問 http://localhost/consumer/dept/list:

test
相關文章
相關標籤/搜索