<?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>cn.lzm</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-consumer-person-80</artifactId>
<dependencies>
<!--引入api模块-->
<dependency>
<groupId>cn.lzm</groupId>
<artifactId>API</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
</dependencies>
</project>
server:
port: 80
package cn.lzm.springcloud.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class WebConfig {
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
package cn.lzm.springcloud.controller;
import cn.lzm.springcloud.pojo.Person;
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.ResponseBody;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* 理解:消费者,不应该有service层
* RestTemplate... 直接调用注册到spring中
* (String url, Class<T> responseType, Map<String, ?> uriVariables)路径 响应类字节码 map请求参数
*/
@Controller
public class PersonController {
@Autowired
RestTemplate restTemplate;
private static final String REQUEST_URL = "http://localhost:8001";
@GetMapping("/person/com/add")
@ResponseBody
public String addPerson(Person person){
//postForObject ,getForObjec ...
return restTemplate.postForObject(REQUEST_URL+"/person/add",person,String.class);
}
@GetMapping("/person/com/get/{id}")
@ResponseBody
public Person getPersonById(@PathVariable("id") int id){
return restTemplate.getForObject(REQUEST_URL+"/person/{id}",Person.class,id);
}
@GetMapping("/person/com/get/all")
@ResponseBody
public List<Person> getPersonAll(){
return restTemplate.getForObject(REQUEST_URL+"/person/getall",List.class);
}
}
原文:https://www.cnblogs.com/xiaominaaaa/p/14058588.html