1、创建普通Meven工程
springcloud-consumer-dept-80
2、导jar包
消费端不需要连接数据库,也就不需要与数据库相关的Mapper层、Service层
<?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.tuwer</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>
<!--自定义API依赖-->
<dependency>
<groupId>com.tuwer</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--web-->
<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>
3、配置application.yml
只需要配个端口即可;不需要数据库相关的配置
server:
port: 80
4、配置 RestTemplate
提供多种便捷访问远程http服务的方法,简单的Restful服务模板
(地址:url, 实体:Map ,Class<T> responseType)
config/configBean.java
package com.tuwer.springcloud.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author 土味儿
* Date 2022/2/10
* @version 1.0
*/
@Configuration
public class ConfigBean {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
5、Controller层
- DepartmentConsumerController.java
@RestController
public class DepartmentConsumerController {
@Autowired
private RestTemplate restTemplate;
/**
* 服务提供者基础路径
*/
private static final String REST_URL_PREFIX = "http://localhost:8001";
@RequestMapping("/dept/get/{id}")
public Department getDepartment(@PathVariable("id") Long id){
// 服务提供者中要求以get方式访问,所以用getForObject()
return restTemplate.getForObject(REST_URL_PREFIX+"/department/get/"+id, Department.class);
}
@RequestMapping("/dept/add")
public boolean addDepartment(Department department){
// postForObject 中传递对象时,在服务提供者接收方法的参数前,加 @RequestBody 注解
return restTemplate.postForObject(REST_URL_PREFIX+"/department/add", department, Boolean.class);
}
@RequestMapping("/dept/getAll")
public List<Department> getAllDepartment(){
return restTemplate.getForObject(REST_URL_PREFIX+"/department/getAll", List.class);
}
}
6、主启动类
@SpringBootApplication
public class DepartmentConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(DepartmentConsumer_80.class,args);
}
}
7、项目结构
8、测试
分别启动 服务提供者、服务消费者