Rest 学习环境搭建
SpringCloud 版本和 SpringBoot版本的选择:
1、父项目搭建
新建Maven项目作为父项目,Packageing是pom模式
导入依赖:
<?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>org.example</groupId>
<artifactId>SpringCloud</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 打包方式 -->
<packaging>pom</packaging>
<properties>
<spring-cloud-version>Hoxton.SR12</spring-cloud-version>
<spring-boot-version>2.3.12.RELEASE</spring-boot-version>
<mysql-connector-java-vesion>8.0.27</mysql-connector-java-vesion>
<druid-version>1.2.8</druid-version>
<mybatis-starter-version>2.2.0</mybatis-starter-version>
<junit-version>4.12</junit-version>
<log4j-core-sersion>2.17.1</log4j-core-sersion>
</properties>
<dependencyManagement>
<dependencies>
<!-- SpringCloud 的依赖 : https://www.springcloud.cc/spring-cloud-greenwich.html#_quick_start-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- SpringBoot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 数据库 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java-vesion}</version>
</dependency>
<!-- 数据源 -->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid-version}</version>
</dependency>
<!-- SpringBoot启动器 -->
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-starter-version}</version>
</dependency>
<!-- junit -->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<!-- Log4j -->
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j-core-sersion}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2、实体类模块搭建
新建子模块 springcloud-api :
依赖:
<?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</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-api</artifactId>
<!-- 当前Model自己需要的依赖,如果父依赖中配置了版本,这里不用写 -->
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
IDEA 连接数据库: jdbc:mysql://localhost:3306?serverTimezone=Asia/Shanghai
创建数据库:
新建表:
CREATE TABLE `dept` (
`dept_no` bigint(20) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`db_source` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`dept_no`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
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());
数据库写完后写实体类:
package com.example.springcloud.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* Dept 实体类
* @author llp
* @date 2022年01月08日 15:19
*/
@Data
@NoArgsConstructor
@Accessors(chain = true) // 链式写法
public class Dept implements Serializable {
private Long deptNo;
private String deptName;
// 看一下这个数据是存在哪个数据库中的字段
// 微服务,一个服务对应一个数据库,同一个信息可能存在不同的数据库中
private String dbSource;
public Dept(String deptName) {
this.deptName = deptName;
}
}
3、服务提供者模块搭建
新建子模块 springcloud-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>SpringCloud</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-provider-dept-8001</artifactId>
<dependencies>
<!-- 我们需要拿到实体类,所以要配置 api model -->
<dependency>
<groupId>com.example</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</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>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- jetty -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<!-- 热部署工具 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
配置文件
application.yml
配置文件:
server:
port: 8001
# myBaits 配置
mybatis:
type-aliases-package: com.example.springcloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
# spring 配置
spring:
application:
name: spring-provider-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/workers?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password:
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">
<!-- mybatis 配置文件 -->
<configuration>
<settings>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 开启驼峰式命名 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
Dao层
DeptDao
package com.example.springcloud.dao;
import com.example.springcloud.pojo.Dept;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author llp
* @date 2022年02月28日 15:14
*/
@Mapper
@Repository
public interface DeptDao {
boolean addDept(Dept dept);
Dept queryDept(Long id);
List<Dept> queryAllDept();
}
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">
<!-- namespace 定义一个对应的 Dao/Mapper 接口 -->
<mapper namespace="com.example.springcloud.dao.DeptDao">
<insert id="addDept" parameterType="Dept">
insert into db_01.dept(dept_name, db_source) VALUES (#{deptName}, DATABASE())
</insert>
<select id="queryDept" resultType="Dept" parameterType="Long">
select * from db_01.dept where dept_no = #{id}
</select>
<select id="queryAllDept" resultType="Dept">
select * from db_01.dept
</select>
</mapper>
Service层
package com.example.springcloud.service;
import com.example.springcloud.pojo.Dept;
import java.util.List;
/**
* @author llp
* @date 2022年02月28日 15:29
*/
public interface DeptService {
boolean addDept(Dept dept);
Dept queryDept(Long id);
List<Dept> queryAllDept();
}
package com.example.springcloud.service.impl;
import com.example.springcloud.dao.DeptDao;
import com.example.springcloud.pojo.Dept;
import com.example.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author llp
* @date 2022年02月28日 15:30
*/
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptDao deptDao;
public boolean addDept(Dept dept) {
return deptDao.addDept(dept);
}
public Dept queryDept(Long id) {
return deptDao.queryDept(id);
}
public List<Dept> queryAllDept() {
return deptDao.queryAllDept();
}
}
Controller层
package com.example.springcloud.controller;
import com.example.springcloud.pojo.Dept;
import com.example.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 提供 restful 接口
* @author llp
* @date 2022年02月28日 15:41
*/
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@PostMapping("/dept/add")
public boolean addDept(@RequestBody Dept dept){
return deptService.addDept(dept);
}
@GetMapping("/dept/get/{id}")
public Dept get(@PathVariable("id") Long id){
return deptService.queryDept(id);
}
@GetMapping("/dept/list")
public List<Dept> queryAll(){
return deptService.queryAllDept();
}
}
主启动器
package com.example.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @desc 启动类
* @auth llp
* @date 2022年02月28日 15:49
*/
@SpringBootApplication
public class DeptProvider_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider_8001.class, args);
}
}
启动访问测试接口。
4、服务消费者模块搭建
引入依赖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</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-consumer-dept-80</artifactId>
<!-- 实体类 + web -->
<dependencies>
<dependency>
<groupId>com.example</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>
配置文件
server:
port: 80
controller层
package com.example.springcloud.controller;
import com.example.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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 java.util.List;
/**
* @desc
* @auth llp
* @date 2022年02月28日 17:39
*/
@RestController
public class DeptConsumerController {
// 消费者,不应该有service层
// RestTemplate , 有对应的请求方法,供我们直接调用,要注册到 Spring 中
private static final String REST_URL_PREFIX = "http://localhost:8001";
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/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);
}
}
配置 RestTemplate
package com.example.springcloud.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @desc
* @auth llp
* @date 2022年02月28日 17:44
*/
@Configuration
public class RestConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
启动项目并测试接口。