Spring Cloud 进阶--Rest 微服务基础模块构建

版权声明:本文为博主原创文章,如果觉得写的不错需要转载,在转载时请注明博文出处! https://blog.csdn.net/Hello_World_QWP/article/details/85912927

                                                  《 Rest 微服务基础模块构建 》

前言

前面进行了微服务架构风格、微服务框架以及微服务相关的理论体系的简介与介绍,本篇博文是微服务实践的开始,本篇博客主要为完成 Rest 微服务基础模块的建设,包括:

  • 整体微服务项目的顶级(父级项目,主要为实现配置共享与版本统一管理,以及插件和资源的加载管理)项目,项目名为  “ microservice ”;
  • 整体微服务项目的公共子模块,供其它子模块引用,达到通用的目的,例如:定义配置、工具、实体,枚举等,每个微服务模块无需再重复定义,直接引用即可,项目名为 “ microservice-api ” ;
  • 微服务提供者子模块,服务名为 “ microservice-provider-8001 ”;
  • 微服务消费者子模块,服务名为 “ microservice-consumer-80 ”;

Rest 微服务基础模块构建

1、Java Working Set

在开始建项目前,为了在复杂的项目结构环境下的管理工作,建议新建一个 Java Working Set,点击左上角 File -> Other -> Java Working Set 集合名自取。

2、父级工程 “ microservice ” (聚合项目)

注意:新建的父工程 microservice,Packaging 是 pom 类型的, File(或者点击项目列表栏空白处) -> Other -> Maven -> Maven Project

作用与目的:主要是定义一个公共的 POM 文件,将后续加入的各个子模块公共的 jar 包等统一提出来,类似一个抽象的父类。

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>

	<description>父级公共模块模块</description>

	<!-- 版本定义 -->
	<properties>
		<project.version>0.0.1-SNAPSHOT</project.version>
		<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>

	<groupId>com.huazai.springcloud</groupId>
	<artifactId>microservice</artifactId>
	<version>${project.version}</version>
	<packaging>pom</packaging>

	<!-- 项目依赖包 -->
	<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>

	<!-- 配置加载的资源以及插件,否则后面项目会报错,无法启动 -->
	<build>
		<finalName>microservicecloud</finalName>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<delimiters>
						<delimit>$</delimit>
					</delimiters>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<!-- 这个是后面新建了多少个模块,这儿就会包含相应的模块 -->
	<modules>
		<module>microservice-api</module>
		<module>microservice-provider-8001</module>
		<module>microservice-consumer-80</module>
		<module>microservice-eureka-7001</module>
		<module>microservice-eureka-7002</module>
		<module>microservice-eureka-7003</module>
		<module>microservice-feign-80</module>
		<module>microservice-provider-8002</module>
		<module>microservice-provider-8003</module>
		<module>microservice-hystrix-8001</module>
		<module>microservice-hystrix-dashboard-9001</module>
		<module>microservice-zuul-6001</module>
		<module>microservice-config-service-5001</module>
		<module>microservice-config-client-4001</module>
		<module>microservice-config-eureka-7001</module>
		<module>microservice-config-provider-8001</module>
	</modules>
</project>

3、公共子模块 “ microservice-api

如下图:

注:这儿创建完成后,回到父工程中可以查看到新添加一个 model 的子模块。

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.huazai.springcloud</groupId>
		<artifactId>microservice</artifactId>
		<version>${project.version}</version>
	</parent>

	<!-- 当前Module的名字 -->
	<artifactId>microservice-api</artifactId>

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



</project>

附建表脚本(注:适用于5.7.22):

-- ----------------------------
-- DATABASE structure for `microservice-01`
-- ----------------------------

DROP DATABASE IF EXISTS microservice-01;
CREATE DATABASE microservice-01 CHARACTER SET UTF8;
USE microservice-01;

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `department`
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `deptno` bigint(20) NOT NULL AUTO_INCREMENT,
  `dname` varchar(60) DEFAULT NULL,
  `db_source` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`deptno`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of department
-- ----------------------------
INSERT INTO `department` VALUES ('1', '开发部', 'microservice-01');
INSERT INTO `department` VALUES ('2', '人事部', 'microservice-01');
INSERT INTO `department` VALUES ('3', '财务部', 'microservice-01');
INSERT INTO `department` VALUES ('4', '市场部', 'microservice-01');
INSERT INTO `department` VALUES ('5', '运维部', 'microservice-01');

作为示例性项目,这儿新建一个部门实体 “ Department ” ,便于后边测试,(这儿还配置使用了 lombok eclipse 插件,去掉了繁琐的get/set操作);实体内容如下:

package com.huazai.springcloud.entity;

import java.io.Serializable;

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

/**
 * 
 * <p>
 * 
 * @ClassName : Department
 *            </p>
 *            <p>
 * @Description : TODO
 *              </p>
 * 
 * @Author : HuaZai
 * @ContactInformation : [email protected]
 * @Date : 2018年05月23日 下午9:00:12
 * @Version : V1.0.0
 * 
 * @param
 */
@SuppressWarnings("unused")
@Accessors(chain = true)
// @AllArgsConstructor
@NoArgsConstructor

@Data
public class Department implements Serializable // 序列化
{
	/**
	 * @Files serialVersionUID : TODO
	 */
	private static final long serialVersionUID = -1362631725686764212L;
	private Long deptno; // 主键
	private String dname; // 部门名称
	private String db_source;// 来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库

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

}

公共子模块创建完成后,需要供其它子模块调用,点击该项目右键 -> Run As -> Maven Client 再 Maven Install 后才能达到公用的目的。这样一来,如果其它子模块还需要使用部门实体的话,就不用每个工程都定义一份,直接引用本模块即可。

4、服务提供者模块 “ microservice-provider-8001 

创建如下图:

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.huazai.springcloud</groupId>
		<artifactId>microservice</artifactId>
		<version>${project.version}</version>
	</parent>

	<artifactId>microservice-provider-8001</artifactId>
	<description>服务提供者模块-8001</description>

	<dependencies>
		<!-- 引入自己定义的api通用包,可以使用Dept部门Entity -->
		<dependency>
			<groupId>com.huazai.springcloud</groupId>
			<artifactId>microservice-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>
		<!-- 将微服务provider侧注册进eureka -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		<!-- actuator与注册微服务信息完善 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<!-- Ribbon相关 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-ribbon</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</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>

YML 定义内容如下(地址和密码需要修改为自己数据库服务器和对应的数据库密码):

server:
  port: 8001
  
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.huazai.springcloud.entity    # 所有Entity别名类所在包
  mapper-locations:
  - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件
    
spring:
   application:
    name: microservice-provider # 该模块的服务提供者的应用名称必须一致
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
    url: jdbc:mysql://000.000.000.000:3306/microservice-01              # 数据库名称
    username: root
    password: **********
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间

MyBatis 配置文件定义:在工程的 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>

部门 Dao 层接口:

package com.huazai.springcloud.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.huazai.springcloud.entity.Department;

@Mapper
public interface DepartmentDao
{
	public boolean addDepartment(Department department);

	public Department findById(Long id);

	public List<Department> findAll();

}

然后在工程的 src/main/resources/mybatis 目录下新建 mapper 文件夹,并在该文件下新建一个 DepartmentMapper.xml 的配置文件,需要与 DepartmentDao 文件对应,具体内容如下:

<?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.huazai.springcloud.dao.DepartmentDao">

	<select id="findById" resultType="Department"
		parameterType="Long">
		select deptno,dname,db_source from department where
		deptno=#{deptno};
	</select>

	<select id="findAll" resultType="Department">
		select deptno,dname,db_source
		from department;
	</select>

	<insert id="addDepartment" parameterType="Department">
		INSERT INTO
		department(dname,db_source) VALUES(#{dname},DATABASE());
	</insert>

</mapper>
 

部门服务 DepartmentService 接口,内容如下:

package com.huazai.springcloud.service;

import java.util.List;

import com.huazai.springcloud.entity.Department;

public interface DepartmentService
{
	public boolean add(Department department);

	public Department get(Long id);

	public List<Department> list();
}

部门服务接口实现 DepartmentServiceImpl 类,内容如下:

package com.huazai.springcloud.service.impl;

import java.util.List;

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

import com.huazai.springcloud.dao.DepartmentDao;
import com.huazai.springcloud.entity.Department;
import com.huazai.springcloud.service.DepartmentService;

@Service
public class DepartmentServiceImpl implements DepartmentService
{

	@Autowired
	private DepartmentDao departmentDao;

	@Override
	public boolean add(Department department)
	{
		return departmentDao.addDepartment(department);
	}

	@Override
	public Department get(Long id)
	{
		return departmentDao.findById(id);
	}

	@Override
	public List<Department> list()
	{
		return departmentDao.findAll();
	}

}

部门控制层 Controller 类,内容如下:

package com.huazai.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.huazai.springcloud.entity.Department;
import com.huazai.springcloud.service.DepartmentService;

@RestController
@RequestMapping(value = "/department")
public class DepartmentController
{

	@Autowired
	private DepartmentService departmentService;

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public boolean add(@RequestBody Department department)
	{
//		Department department =  new Department(name);
		return departmentService.add(department);
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
	public void delete(@PathVariable Long id)
	{
		System.out.println(id);
	}

	@RequestMapping(value = "/update", method = RequestMethod.PUT)
	public void update(@RequestBody Department department)
	{

	}

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

	@RequestMapping(value = "/list")
	public List<Department> list()
	{
		return departmentService.list();
	}

}

微服务提供者主启动类,内容如下:

package com.huazai.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description
 *              <li>服务提供者1号服务器
 *              </ul>
 * @className MicroserviceProviderApp_8001
 * @package com.huazai.springcloud
 * @createdTime 2018年05月23日 下午2:21:44
 *
 * @version V1.0.0
 */
@SpringBootApplication
public class MicroserviceProviderApp_8001
{

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

微服务提供者模块创建完成后,工程总览,如下图:

测试微服务提供者,是否能正常访问,启动微服务后访问微服务地址 ,正常有数据就OK咯,如下图:

5、服务消费者模块 “ microservice-consumer-80

创建如下图:

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.huazai.springcloud</groupId>
		<artifactId>microservice</artifactId>
		<version>${project.version}</version>
	</parent>

	<artifactId>microservice-consumer-80</artifactId>
	<description>服务消费者模块-consumer-80</description>

	<!-- 项目依赖包 -->
	<dependencies>
		<dependency><!-- 自己定义的api -->
			<groupId>com.huazai.springcloud</groupId>
			<artifactId>microservice-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>
		<!-- Ribbon相关 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-ribbon</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
	</dependencies>


</project>

YML 配置内容:

server:
  port: 80

配置 Bean ConfigBean 类,类似于 Spring 里面的 applicationContext.xml 中的注入 Bean,内容如下:

package com.huazai.springcloud.cfgbeans;

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

/**
 * 
 * <p>
 * 
 * @ClassName : ConfigBean
 *            </p>
 *            <p>
 * @Description : TODO
 *              </p>
 * 
 * @Author : HuaZai
 * @ContactInformation : [email protected]
 * @Date : 2018年05月23日 下午9:01:21
 * @Version : V1.0.0
 * 
 * @param
 */
@Configuration
public class ConfigBean
{
	@Bean
	public RestTemplate getRestTemplate()
	{
		return new RestTemplate();
	}
}

消费者 DepartmentController 类:

package com.huazai.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 org.springframework.web.client.RestTemplate;

import com.huazai.springcloud.entity.Department;

/**
 * 
 * <p>
 * 
 * @ClassName : DepartmentController
 *            </p>
 *            <p>
 * @Description : TODO
 *              </p>
 * 
 * @Author : HuaZai
 * @ContactInformation : [email protected]
 * @Date : 2018年05月23日 下午9:01:38
 * @Version : V1.0.0
 * 
 * @param
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/department")
public class DepartmentController
{

	/**
	 * 初级 -> 通过 Spring 的 RestTemplate + 服务提供者地址进行访问
	 */
	@SuppressWarnings("unused")
	private static final String BASE_URL_PREFIX = "http://localhost:8001/department";
	/**
	 * 终极 -> 通过 Spring 的 RestTemplate + Eureka 注册中心服务列表的提供者应用名称进行访问
	 * (Ribbon和Eureka整合后Consumer可以直接调用服务而不用再关心地址和端口号)
	 */
	private static final String BASE_APPLICATION_URL_PREFIX = "http://MICROSERVICE-PROVIDER/department";

	@Autowired
	private RestTemplate restTemplate;

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public boolean add(@RequestBody Department department)
	{
		return restTemplate.postForObject(BASE_URL_PREFIX + "/add", department, Boolean.class);
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
	public void delete(@PathVariable Long id)
	{
		restTemplate.delete(BASE_URL_PREFIX + "/delete/" + id, id);
	}

	@RequestMapping(value = "/update", method = RequestMethod.PUT)
	public void update(@RequestBody Department department)
	{
		restTemplate.put(BASE_URL_PREFIX + "/update", department, Department.class);
	}

	@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
	public Department get(@PathVariable Long id)
	{
		return restTemplate.getForObject(BASE_URL_PREFIX + "/get/" + id, Department.class);
	}

	@RequestMapping(value = "/list")
	public List<Department> list()
	{
		return restTemplate.getForObject(BASE_URL_PREFIX + "/list", List.class);
	}
}

关于 RestTemplate:

RestTemplate 提供了多种便捷访问远程 Http 服务的方法,是一种简单便捷的访问 restful 服务模板类,是 Spring 提供的用于访问 Rest 服务的客户端模板工具集。
有关 RestTemplate 更多使用,请参考官网:《 Spring 官网说明 》

消费者微服务启动 MicroServiceConsumerApp 类,内容如下:

package com.huazai.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description
 *              <li>服务消费者
 *              </ul>
 * @className MicroServiceConsumerApp
 * @package com.huazai.springcloud
 * @createdTime 2018年05月22日 下午3:47:02
 *
 * @version V1.0.0
 */
@SpringBootApplication
@EnableEurekaClient
public class MicroServiceConsumerApp
{

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

微服务消费者模块创建完成后,项目概览如下图:

启动测试,首先启动 “ 服务提供者 ” 模块,再启动 “ 服务消费者 ” 模块,在浏览器地址栏,输入 “ 项目地址 + Base Uri ” ,输出内容如下,说明关于微服务基础模块建设完成了,如下图:

GitLab 源码地址:

项目源码地址(zip格式的工程包):


好了,关于 Spring Cloud 进阶--Rest 微服务基础模块构建 就写到这儿了,如果还有什么疑问或遇到什么问题欢迎扫码提问,也可以给我留言哦,我会一一详细的解答的。 
歇后语:“ 共同学习,共同进步 ”,也希望大家多多关注CSND的IT社区。


作       者: 华    仔
联系作者: [email protected]
来        源: CSDN (Chinese Software Developer Network)
原        文: https://blog.csdn.net/Hello_World_QWP/article/details/85912927
版权声明: 本文为博主原创文章,请在转载时务必注明博文出处!

猜你喜欢

转载自blog.csdn.net/Hello_World_QWP/article/details/85912927
今日推荐