🚌一个人可以走的很快,一群人可以走的很远
🎉点赞➕评论➕收藏 ➕关注== 养成习惯(一键四连)📝
🎉欢迎关注💗一起学习👍一起讨论⭐️一起进步📝
🙏作者水平有限,欢迎各位大佬指点,相互学习进步!😆
1、通过RestTemplate传参
1.1、简介
spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
在Spring应用程序中访问第三方REST服务与使用Spring RestTemplate类有关。RestTemplate类的设计原则与许多其他Spring的模板类(例如JdbcTemplate、JmsTemplate)相同,为执行复杂任务提供了一种具有默认行为的简化方法。
RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。
考虑到RestTemplate类是为调用REST服务而设计的,因此它的主要方法与REST的基础紧密相连就不足为奇了,后者是HTTP协议的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如,RestTemplate类具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。
1.2、使用第二章节ribbon模块代码
在nacos-provider项目中创建get、post的接口
DataGetRequestController
package com.nacosprovider;
import com.nacosprovider.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class DataGetRequestController {
@GetMapping("/getInt")
public int getInt(int id){
return id;
}
@GetMapping(value = "/getBox",produces = {"application/json;charset=utf-8"})
public String getBox(String name,Integer id){
return "name = " + name + " id = " + id;
}
@GetMapping("/getReuqestParam")
public String getReuqestParam(@RequestParam(value = "rp",required = false) Integer id){
return "ID = " + id;
}
@GetMapping(value = "/getUser",produces = {"application/json;charset=utf-8"})
public User getUser(User user){
return user;
}
@GetMapping("/getIds")
public List<Long> getIds(@RequestParam List<Long> ids){
return ids;
}
@GetMapping(value = "/getMap",produces = {"application/json;charset=utf-8"})
public Map<String,Object> getMap(@RequestParam Map<String,Object> map){
return map;
}
@GetMapping(value = "/getObj",produces = {"application/json;charset=utf-8"})
public Object getObj(@RequestParam(name = "ik",required = true,defaultValue = "500") Integer id){
return id;
}
@GetMapping("/getArr")
public String[] getArr(String[] arr){
return arr;
}
@GetMapping(value = "/getList",produces = {"application/json;charset=utf-8"})
public List<String> getList(@RequestParam List<String> names){
return names;
}
}
DataPostRequestController
package com.nacosprovider;
import com.nacosprovider.entity.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class DataPostRequestController {
@PostMapping("/postInt")
public int postInt(int id){
return id;
}
@PostMapping("/postBox")
public String postBox(String name,Integer id){
return "name = " + name +" id = " + id;
}
/**
* @RequestBody:
* 要求请求参数必须是在body中的
*
* 如果不加@RequestBody:
* 请求可以放在parameter、body中
* 复杂对象也是可以传的
* @param user
* @return
*/
@PostMapping("/postUser")
public User postUser(@RequestBody User user){
return user;
}
@PostMapping("/postUserNoBody")
public User postUserNoBody( User user){
return user;
}
@PostMapping(value = "/postUser2",produces = {"application/json;charset=utf-8"})
public User postUser2(@RequestBody User user){
return user;
}
@PostMapping("/postIds")
public List<Integer> postIds(@RequestBody List<Integer> ids){
return ids;
}
@PostMapping("/postUsers")
public List<User> postUsers(@RequestBody List<User> users){
return users;
}
@PostMapping("/postMap")
public Map<String,Object> postMap(@RequestBody Map<String,Object> map){
return map;
}
}
1.3、nacos-consumer中新增测试依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
1.4、测试
在test包中创建类:DataGetRequestControllerTest,测试get
package com.nacosconsumer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import java.util.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DataGetRequestControllerTest {
@Autowired
RestTemplate restTemplate;
@Test
public void getInt(){
Map<String,Object> params = new HashMap<>();
params.put("id",10);
ResponseEntity<Integer> responseEntity = restTemplate.getForEntity("http://nacos-provider/getInt?id={id}",Integer.class,params);
Integer ret = responseEntity.getBody();
System.out.println(ret);
responseEntity = restTemplate.getForEntity("http://nacos-provider/getInt?id=10",Integer.class,params);
ret = responseEntity.getBody();
System.out.println(ret);
}
@Test
public void getBox(){
Map<String,Object> params = new HashMap<>();
params.put("name","小黑");
params.put("id",100);
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://nacos-provider/getBox?name={name}&id={id}",String.class,params);
String ret = responseEntity.getBody();
System.out.println(ret);
responseEntity = restTemplate.getForEntity("http://nacos-provider/getBox?name=小黑&id=100",String.class,params);
ret = responseEntity.getBody();
System.out.println(ret);
}
@Test
public void getReuqestParam(){
Map<String,Object> params = new HashMap<>();
params.put("rp",100);
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://nacos-provider/getReuqestParam?rp={rp}",String.class,params);
String ret = responseEntity.getBody();
System.out.println(ret);
responseEntity = restTemplate.getForEntity("http://nacos-provider/getReuqestParam?rp=100",String.class,params);
ret = responseEntity.getBody();
System.out.println(ret);
String retObj = restTemplate.getForObject("http://nacos-provider/getReuqestParam?rp=100",String.class,params);
System.out.println(retObj);
}
@Test
public void getUser(){
Map<String,Object> params = new HashMap<>();
params.put("id",10);
params.put("name","admin");
params.put("password","123456");
ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://nacos-provider/getUser?id={id}&name={name}&password={password}",User.class,params);
User user = responseEntity.getBody();
System.out.println(user);
}
@Test
public void getIds(){
Map<String,Object> params = new HashMap<>();
params.put("ids","1,2,3,4,5");
ResponseEntity<ArrayList> responseEntity = restTemplate.getForEntity("http://nacos-provider/getIds?ids={ids}", ArrayList.class,params);
List<Long> ids = responseEntity.getBody();
System.out.println(ids);
}
@Test
public void getMap(){
Map<String,Object> params = new HashMap<>();
params.put("name","小火锅");
params.put("salary","3000");
ResponseEntity<Map> responseEntity = restTemplate.getForEntity("http://nacos-provider/getMap?name={name}&salary={salary}", Map.class,params);
Map ret = responseEntity.getBody();
System.out.println(ret);
}
@Test
public void getObj(){
Map<String,Object> params = new HashMap<>();
params.put("ik",300);
ResponseEntity<Object> responseEntity = restTemplate.getForEntity("http://nacos-provider/getObj?ik={ik}", Object.class,params);
Object ret = responseEntity.getBody();
System.out.println(ret);
}
@Test
public void getArr(){
Map<String,Object> params = new HashMap<>();
params.put("arr","1,2,3");
ResponseEntity<String[]> responseEntity = restTemplate.getForEntity("http://nacos-provider/getArr?arr={arr}", String[].class,params);
String[] ret = responseEntity.getBody();
Arrays.stream(ret).forEach(System.out::println);
}
@Test
public void getList(){
Map<String,Object> params = new HashMap<>();
params.put("names","1,2,3");
ResponseEntity<ArrayList> responseEntity = restTemplate.getForEntity("http://nacos-provider/getList?names={names}", ArrayList.class,params);
List<String> ret = responseEntity.getBody();
ret.forEach(System.out::println);
}
}
在test包中创建类:DataPostRequestControllerTest,测试post
package com.nacosconsumer;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DataPostRequestControllerTest {
@Autowired
RestTemplate restTemplate;
@Test
public void postInt(){
MultiValueMap<String, Integer> map= new LinkedMultiValueMap<>();
map.add("id",100);
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Integer>> request = new HttpEntity<>(map, headers);
ResponseEntity<Integer> ret = restTemplate.postForEntity("http://nacos-provider/postInt",request,Integer.class);
System.out.println(ret);
}
@Test
public void postBox(){
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.put("name", Collections.singletonList("小黑"));
map.add("id","100");
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> ret = restTemplate.postForEntity("http://nacos-provider/postBox",request,String.class);
System.out.println(ret.getBody());
}
@Test
public void postUser(){
User user = new User();
user.setId(100L);
user.setName("小火锅");
user.setPassword("123456");
ResponseEntity<User> ret = restTemplate.postForEntity("http://nacos-provider/postUser",user,User.class);
System.out.println(ret.getBody());
}
@Test
public void postUserNoBody(){
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.put("name", Collections.singletonList("小黑"));
map.add("id","100");
map.put("password", Collections.singletonList("123456"));
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<User> ret = restTemplate.postForEntity("http://nacos-provider/postUserNoBody",request,User.class);
System.out.println(ret.getBody());
}
@Test
public void postUser2(){
User user = new User();
user.setId(100L);
user.setName("小火锅");
user.setPassword("123456");
ResponseEntity<User> ret = restTemplate.postForEntity("http://nacos-provider/postUser2",user,User.class);
System.out.println(ret.getBody());
}
@Test
public void postIds(){
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(1);
ids.add(1);
ids.add(1);
ids.add(1);
ResponseEntity<ArrayList> ret = restTemplate.postForEntity("http://nacos-provider/postIds",ids,ArrayList.class);
System.out.println(ret.getBody());
}
@Test
public void postUsers(){
User user = new User();
user.setId(100L);
user.setName("小火锅");
user.setPassword("123456");
List<User> users = new ArrayList<>();
users.add(user);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(JSON.toJSONString(users), headers);
ResponseEntity<ArrayList> ret = restTemplate.postForEntity("http://nacos-provider/postUsers",request,ArrayList.class);
List<User> retUsers = ret.getBody();
System.out.println(retUsers);
}
@Test
public void postMap(){
Map<String,Object> params = new HashMap<>();
params.put("id",100);
params.put("爱好","摩托、轮滑、越野、帆船");
Map<String,Object> ret = restTemplate.postForObject("http://nacos-provider/postMap",params,HashMap.class);
System.out.println(ret);
}
}
2、通过feign传参
1.1、简介
Feign is a declarative web service client. It makes writing web
service clients easier. To use Feign create an interface and annotate
it. It has pluggable annotation support including Feign annotations
and JAX-RS annotations. Feign also supports pluggable encoders and
decoders. Spring Cloud adds support for Spring MVC annotations and for
using the same HttpMessageConverters used by default in Spring Web.
Spring Cloud integrates Eureka, Spring Cloud CircuitBreaker, as well
as Spring Cloud LoadBalancer to provide a load-balanced http client
when using Feign.Feign是一个声明式 Web 服务客户端。它使编写 Web 服务客户端变得更容易。要使用 Feign
创建一个接口并对其进行注释。它具有可插入的注释支持,包括 Feign 注释和 JAX-RS 注释。Feign
还支持可插拔的编码器和解码器。Spring Cloud 添加了对 Spring MVC
注解的支持,并支持使用HttpMessageConvertersSpring Web 中默认使用的注解。Spring Cloud 集成了
Eureka、Spring Cloud CircuitBreaker 和 Spring Cloud LoadBalancer,在使用
Feign 时提供负载均衡的 http 客户端。https://docs.spring.io/spring-cloud/docs/2020.0.3/reference/htmlsingle/#spring-cloud-openfeign
1.2、使用第二章节feign模块代码
在nacos-provider项目中创建get、post的接口
DataGetRequestController
package com.nacosprovider;
import com.nacosprovider.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class DataGetRequestController {
@GetMapping("/getInt")
public int getInt(int id){
return id;
}
@GetMapping(value = "/getBox",produces = {"application/json;charset=utf-8"})
public String getBox(String name,Integer id){
return "name = " + name + " id = " + id;
}
@GetMapping("/getReuqestParam")
public String getReuqestParam(@RequestParam(value = "rp",required = false) Integer id){
return "ID = " + id;
}
@GetMapping(value = "/getUser",produces = {"application/json;charset=utf-8"})
public User getUser(User user){
return user;
}
@GetMapping("/getIds")
public List<Long> getIds(@RequestParam List<Long> ids){
return ids;
}
@GetMapping(value = "/getMap",produces = {"application/json;charset=utf-8"})
public Map<String,Object> getMap(@RequestParam Map<String,Object> map){
return map;
}
@GetMapping(value = "/getObj",produces = {"application/json;charset=utf-8"})
public Object getObj(@RequestParam(name = "ik",required = true,defaultValue = "500") Integer id){
return id;
}
@GetMapping("/getArr")
public String[] getArr(String[] arr){
return arr;
}
@GetMapping(value = "/getList",produces = {"application/json;charset=utf-8"})
public List<String> getList(@RequestParam List<String> names){
return names;
}
}
DataPostRequestController
package com.nacosprovider;
import com.nacosprovider.entity.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class DataPostRequestController {
@PostMapping("/postInt")
public int postInt(int id){
return id;
}
@PostMapping("/postBox")
public String postBox(String name,Integer id){
return "name = " + name +" id = " + id;
}
/**
* @RequestBody:
* 要求请求参数必须是在body中的
*
* 如果不加@RequestBody:
* 请求可以放在parameter、body中
* 复杂对象也是可以传的
* @param user
* @return
*/
@PostMapping("/postUser")
public User postUser(@RequestBody User user){
return user;
}
@PostMapping("/postUserNoBody")
public User postUserNoBody( User user){
return user;
}
@PostMapping(value = "/postUser2",produces = {"application/json;charset=utf-8"})
public User postUser2(@RequestBody User user){
return user;
}
@PostMapping("/postIds")
public List<Integer> postIds(@RequestBody List<Integer> ids){
return ids;
}
@PostMapping("/postUsers")
public List<User> postUsers(@RequestBody List<User> users){
return users;
}
@PostMapping("/postMap")
public Map<String,Object> postMap(@RequestBody Map<String,Object> map){
return map;
}
}
1.3、nacos-consumer中新增测试依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
1.4、增加DataGetRequestService
package com.nacosconsumer;
import com.nacosconsumer.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
@FeignClient(value = "nacos-provider",contextId = "DataGetRequestService")
public interface DataGetRequestService {
@RequestMapping("/getInt")
int getInt(@RequestParam("id") int id);
@RequestMapping("/getBox")
String getBox(@RequestParam("name") String name,@RequestParam("id") Integer id);
@RequestMapping("/getReuqestParam")
String getReuqestParam(@RequestParam("rp") Integer id);
@RequestMapping("/getUser")
User getUser(@SpringQueryMap User user);
@RequestMapping("/getIds")
List<Long> getIds(@RequestParam("ids") List<Long> ids);
@RequestMapping("/getMap")
Map<String,Object> getMap(@RequestParam Map<String,Object> map);
@RequestMapping("/getObj")
Object getObj(@RequestParam(name = "ik",required = true,defaultValue = "500") Integer id);
@RequestMapping("/getArr")
String[] getArr(@RequestParam String[] arr);
@RequestMapping("/getList")
List<String> getList(@RequestParam List<String> names);
}
1.5、增加DataPostRequestService
package com.nacosconsumer;
import com.nacosconsumer.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
@FeignClient(value = "nacos-provider",contextId = "DataPostRequestService")
public interface DataPostRequestService {
@PostMapping("/postInt")
int postInt(@RequestParam("id") int id);
@PostMapping("/postBox")
String postBox(@RequestParam("name") String name,@RequestParam("id") Integer id);
@PostMapping("/postUser")
User postUser(@RequestBody User user);
@PostMapping("/postUserNoBody")
User postUserNoBody(User user);
@PostMapping("/postUser2")
User postUser2(@RequestBody User user);
@PostMapping("/postIds")
List<Integer> postIds(@RequestBody List<Integer> ids);
@PostMapping("/postUsers")
List<User> postUsers(@RequestBody List<User> users);
@PostMapping("/postMap")
Map<String,Object> postMap(@RequestBody Map<String,Object> map);
}
1.6、测试
在test包中创建类DataGetRequestServiceTests
package com.nacosconsumer;
import com.nacosconsumer.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DataGetRequestServiceTests {
@Autowired
DataGetRequestService dataGetRequestService;
@Test
public void getInt(){
int ret = dataGetRequestService.getInt(10);
System.out.println(ret);
}
@Test
public void getBox(){
String ret = dataGetRequestService.getBox("admin",10);
System.out.println(ret);
}
@Test
public void getReuqestParam(){
String ret = dataGetRequestService.getReuqestParam(10);
System.out.println(ret);
}
@Test
public void getUser(){
User user = new User();
user.setId(1L);
user.setName("小黑");
user.setPassword("123456");
User ret = dataGetRequestService.getUser(user);
System.out.println(ret);
}
@Test
public void getIds(){
List<Long> ids = new ArrayList<>();
ids.add(1L);
ids.add(2L);
ids.add(3L);
List<Long> ret = dataGetRequestService.getIds(ids);
System.out.println(ret);
}
@Test
public void getMap(){
Map<String,Object> params = new HashMap<>();
params.put("name","小火锅");
params.put("id",100);
params.put("hobby","轮滑、摩托、越野");
Map<String,Object> ret = dataGetRequestService.getMap(params);
System.out.println(ret);
}
@Test
public void getObj(){
Object ret = dataGetRequestService.getObj(100);
System.out.println(ret);
}
@Test
public void getArr(){
String[] arr = {"1","小辣条","3000"};
String[] ret = dataGetRequestService.getArr(arr);
Arrays.stream(ret).forEach(System.out::println);
}
@Test
public void getList(){
List<String> list = Arrays.asList("100","小辣条","3000");
List<String> ret = dataGetRequestService.getList(list);
ret.forEach(System.out::println);
}
}
在test包中创建类:DataPostRequestServiceTest
package com.nacosconsumer;
import com.nacosconsumer.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DataPostRequestServiceTest {
@Autowired
DataPostRequestService dataPostRequestService;
@Test
public void postInt(){
Integer ret = dataPostRequestService.postInt(100);
System.out.println(ret);
}
@Test
public void postBox(){
String ret = dataPostRequestService.postBox("小火锅",100);
System.out.println(ret);
}
@Test
public void postUser(){
User user = new User();
user.setId(1L);
user.setName("周杰伦");
user.setPassword("123456");
User ret = dataPostRequestService.postUser(user);
System.out.println(ret);
}
/**
* 不支持
*/
@Test
public void postUserNoBody(){
User user = new User();
user.setId(1L);
user.setName("周杰伦");
user.setPassword("123456");
User ret = dataPostRequestService.postUserNoBody(user);
System.out.println(ret);
}
@Test
public void postUser2(){
User user = new User();
user.setId(1L);
user.setName("周杰伦");
user.setPassword("123456");
User ret = dataPostRequestService.postUser2(user);
System.out.println(ret);
}
@Test
public void postIds(){
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
List<Integer> ret = dataPostRequestService.postIds(ids);
System.out.println(ret);
}
@Test
public void postUsers(){
User user = new User();
user.setId(1L);
user.setName("周杰伦");
user.setPassword("123456");
List<User> users = new ArrayList<>();
users.add(user);
List<User> ret = dataPostRequestService.postUsers(users);
System.out.println(ret);
}
@Test
public void postMap(){
Map<String,Object> params = new HashMap<>();
params.put("id",100);
params.put("name","小火锅");
params.put("salary",3000);
Map<String,Object> ret = dataPostRequestService.postMap(params);
System.out.println(ret);
}
}