Springcloud-Rest微服务构建
Posted guardwhy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springcloud-Rest微服务构建相关的知识,希望对你有一定的参考价值。
1.1 总体介绍
1、项目会使用一个Dept部门模块做一个微服务通用案例
Consumer消费者(Client)通过REST调用Provider提供者(Server)提供的服务。
Maven的分包分模块架构
一个简单的Maven模块结构是这样的:
-- app-parent:一个父项目(app-parent)聚合很多子项目(app-util,app-dao,app-web...)
|-- pom.xml
|
|-- app-core
||----pom.xml
|
|-- app-web
||----pom.xml
......
一个父工程带着多个子Module子模块,SpringCloud父工程(Project)下初次带着3个子模块(Module)
- springcloud-api 【封装的整体pojo / 接口 / 公共配置等】。
- springcloud-provider-dept-8001【服务提供者】。
- springcloud-consumer-dept-80【服务消费者】
2、创建数据库db_springclound
-- 创建数据库
create database db_springclound1;
-- 使用数据库
use db_springclound1;
-- 创建员工表
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());
insert into dept(dname,db_source) values(\'后勤部\',database());
1.2 创建父工程
新建父工程Maven项目 springcloud-parent
,切记Packageing是pom模式,倒入相关依赖。
springcloud-parent pom.xml
<?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>cn.guardwhy</groupId>
<artifactId>springcloud-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>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>Hoxton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- spring-boot依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--数据源druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<!-- mybatis-spring-boot启动器-->
<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>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
1.3创建api公共模块
新建springcloud-api模块
1、导入springcloud-api 的 pom.xml
<?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>springcloud-parent</artifactId>
<groupId>cn.guardwhy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-api</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--当前Module需要到的jar包,按自己需求添加,如果父项目已经包含了,可以不用写版本号-->
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
2、编写部门实体类
注意: 实体类需要实例化
package cn.guardwhy.springcloud.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
// Dept实体类
public class Dept implements Serializable {
// 主键
private Long deptno;
// 部门名称
private String dname;
// 来自哪个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存到多个不同的数据库
private String db_source;
}
1.4 创建provider模块
新建springcloud-provider-dept-8001模块
1、导入springcloud-provider-dept-8001的pom.xml
<?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>springcloud-parent</artifactId>
<groupId>cn.guardwhy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-provider-dept-8001</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!--引入自定义的模块,我们就可以使用这个模块中的类了-->
<dependency>
<groupId>cn.guardwhy</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<!--数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<!-- mybatis-spring-boot启动器-->
<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-test</artifactId>
</dependency>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
2、编辑 application.yml
server:
port: 8001
# mybatis的配置
mybatis:
type-aliases-package: cn.guardwhy.springcloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/cn/guardwhy/mapper/*.xml
#spring的相关配置
spring:
application:
name: springcloud-provider-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 数据源
driver-class-name: org.gjt.mm.mysql.Driver # mysql驱动
url: jdbc:mysql://localhost:3306/db_springclound?useUnicode=true&characterEncoding=utf8&useSSL=false #数据库名称
username: root
password: root
dbcp2:
min-idle: 5 #数据库连接池的最小维持连接数
initial-size: 5 #初始化连接数
max-total: 5 #最大连接数
max-wait-millis: 200 #等待连接获取的最大超时时间
3、编辑mybatis-config.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>
4、编写部门的dao接口
package cn.guardwhy.springcloud.dao;
import cn.guardwhy.springcloud.pojo.Dept;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface DeptDao {
// 1.添加一个部门
boolean addDept(Dept dept);
// 2.根据id查询部门
Dept queryById(Long id);
// 3.查询所有的部门
List<Dept> queryAll();
}
5、编写对应的DeptDaoMapper.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">
<!--
实体类的映射文件: namespace 指定接口的类全名
-->
<mapper namespace="cn.guardwhy.springcloud.dao.DeptDao">
<!--1.添加一个部门-->
<insert id="addDept" parameterType="Dept">
insert into dept(dname,db_source) values (#{dname}, DATABASE())
</insert>
<!--2.根据id查询部门-->
<select id="queryById" resultType="Dept" parameterType="Long">
select deptno,dname,db_source from dept where deptno = #{deptno};
</select>
<!--3.查询所有部门-->
<select id="queryAll" resultType="Dept">
select * from dept;
</select>
</mapper>
6、创建对应的Service服务层
package cn.guardwhy.springcloud.service;
import cn.guardwhy.springcloud.pojo.Dept;
import java.util.List;
public interface DeptService {
// 1.添加一个部门
boolean addDept(Dept dept);
// 2.根据id查询部门
Dept queryById(Long id);
// 3.查询所有的部门
List<Dept> queryAll();
}
7、ServiceImpl实现类
package cn.guardwhy.springcloud.service.impl;
import cn.guardwhy.springcloud.dao.DeptDao;
import cn.guardwhy.springcloud.pojo.Dept;
import cn.guardwhy.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
// 1.自动注入
@Autowired
private DeptDao deptDao;
@Override
public boolean addDept(Dept dept) {
return deptDao.addDept(dept);
}
@Override
public Dept queryById(Long id) {
return deptDao.queryById(id);
}
@Override
public List<Dept> queryAll() {
return deptDao.queryAll();
}
}
8、创建对应的DeptController
package cn.guardwhy.springcloud.controller;
import cn.guardwhy.springcloud.pojo.Dept;
import cn.guardwhy.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
// 提供Restful服务!!
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@PostMapping("/dept/add")
public boolean addDept(Dept dept){
return deptService.addDept(dept);
}
@GetMapping("/dept/get/{id}")
public Dept get(@PathVariable("id") Long id){
return deptService.queryById(id);
}
@PostMapping("/dept/list")
public List<Dept> queryAll(){
return deptService.queryAll();
}
}
9、编写DeptProvider的主启动类
package cn.guardwhy.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DeptProvider8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider8001.class, args);
}
}
10、启动项目,查看执行结果。
1.5 创建consumer模块
新建springcloud-consumer-dept-80模块
1、导入相关依赖支持
<?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>springcloud-parent</artifactId>
<groupId>cn.guardwhy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-consumer-dept-80</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!--实体类+web-->
<dependency>
<groupId>cn.guardwhy</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
2、application.yml
server:
port: 80
3、创建一个ConfigBean
配置类注入 RestTemplate
RestTemplate提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集。
使用RestTemplate访问restful接口非常的简单(url,requsetMap,ResponseBean.class) 这三个参数分别代表REST请求地址,请求参数,Http响应转换被转换成的对象类型。
package cn.guardwhy.springcloud.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ConfigBean { // @Configuration -- spring applicationContext.xml
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
4、创建对应的controller
package cn.guardwhy.springcloud.controller;
import cn.guardwhy.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
public class DeptConsumerController {
// RestTemplate: 直接调用就可以了,直接注册到Spring中
//(url, 实体:map, Class<T> responseType)这三个参数分别代表REST请求地址,请求参数,Http响应转换被转换成的对象类型
@Autowired
private RestTemplate restTemplate; // 提供多种便捷访问远程http服务的方法,简单的Restful服务模板!!
// 1.定义成常量
private static final String REST_URL_PREFIX = "http://localhost:8001";
@PostMapping("/consumer/dept/add")
public boolean add(Dept dept){
return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept,Boolean.class);
}
@RequestMapping("/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id){
return restTemplate.getForObject(REST_URL_PREFIX +"/dept/get/"+ id,Dept.class);
}
@RequestMapping("/consumer/dept/list")
public List<Dept> list(){
return restTemplate.getForObject(REST_URL_PREFIX +"/dept/list", List.class);
}
}
5、创建主启动类
package cn.guardwhy.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DeptConsumer80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer80.class,args);
}
}
6、分别启动provider模块
和consumer模块
,查看执行结果。
以上是关于Springcloud-Rest微服务构建的主要内容,如果未能解决你的问题,请参考以下文章
SpringCloud系列四:Eureka 服务发现框架(定义 Eureka 服务端Eureka 服务信息Eureka 发现管理Eureka 安全配置Eureka-HA(高可用) 机制Eur(代码片段